ch1-reciprocal
Chapter_1 | make |
CONTENTS:
folder_reciprocal
(readme.txt,
folder_include,
folder_src)
folder_include
(reciprocal.hpp)
folder_src
(reciprocal.cpp,
main.c)
folder reciprocal (readme.txt, folder_include, folder_src)
readme.txt ALP, p. 19-20
Open the terminal in folder reciprocal (Ctrl+Alt+T or F4).
Compile without linking:
gcc -c -I ./include ./src/main.c
gcc -c -D NDEBUG=3 -O2 -I ./include ./src/main.c
g++ -c -I ./include ./src/reciprocal.cpp
g++ -c -D NDEBUG=3 -O2 -I ./include ./src/reciprocal.cpp
Link object files and output the executable `reciprocal':
g++ main.o reciprocal.o -o reciprocal
g++ *.o -o reciprocal
Run the program:
./reciprocal
Usage: ./reciprocal n
n - integer
./reciprocal 1
The reciprocal of 1 is 1
./reciprocal 10
The reciprocal of 10 is 0.1
./reciprocal 7
The reciprocal of 7 is 0.142857
./reciprocal 0
The reciprocal of 0 is inf
NDEBUG disables run-time errors, to focus on programming errors. See:
https://cplusplus.com/reference/cassert/assert/
Clean:
rm *.o
folder include (reciprocal.hpp)
reciprocal.hpp ALP, p. 19
#ifdef __cplusplus
extern "C"
{
#endif
extern double reciprocal (int i);
#ifdef __cplusplus
}
#endif
folder src (reciprocal.cpp, main.c)
reciprocal.cpp ALP, p. 19
#include <cassert> // for assert()
#include "reciprocal.hpp" // for reciprocal()
double reciprocal (int i)
{
// i should be non-zero
assert (i != 0);
return 1.0 / i;
}
/*
g++ -c -I ./include ./src/reciprocal.cpp
g++ -c -D NDEBUG=3 -O2 -I ./include ./src/reciprocal.cpp
*/
main.c ALP, p. 18-19
#include <stdio.h> // for printf(), fprintf(), stderr
#include <stdlib.h> // for atoi()
#include "reciprocal.hpp" // for reciprocal()
int main (int argc, char **argv)
{
if (argc != 2)
{
fprintf(stderr, "Usage: ./reciprocal n\n");
fprintf(stderr, "n - integer\n");
return 1; // end program, signalling error
}
int i;
i = atoi (argv[1]);
printf ("The reciprocal of %d is %g\n", i, reciprocal (i));
return 0; // end program normally
}
/*
gcc -c -I ./include ./src/main.c // compile without linking
gcc -c -D NDEBUG=3 -O2 -I ./include ./src/main.c
g++ -c -I ./include ./src/reciprocal.cpp
g++ -c -D NDEBUG=3 -O2 -I ./include ./src/reciprocal.cpp
Link object files and output the executable `reciprocal':
g++ main.o reciprocal.o -o reciprocal
g++ *.o -o reciprocal
./reciprocal
Usage: ./reciprocal n
n - integer
./reciprocal 1
The reciprocal of 1 is 1
./reciprocal 10
The reciprocal of 10 is 0.1
./reciprocal 7
The reciprocal of 7 is 0.142857
./reciprocal 0
The reciprocal of 0 is inf
rm *.o // clean
*/
Chapter_1 | BACK_TO_TOP | make |
Comments
Post a Comment