What is G++?It's a cpp compiler which is a part from GNU Compiler Collection(gcc)
What we will do in this post?
We will write a simple C++ and C code then Compile them using gcc
Tools we need:
Text Editor (I use vim)
Command line knowledge
Linux distro
LETS'S START
Step 1:
write the main file which will be a C file
#include<stdio.h>Don't do anything else, as u can c that there is a header file called reciprocal.hpp
#include"reciprocal.hpp"
int main(char argc, char **argv){
int i;
i = atoi(argv[1]);
printf("The reciprocal of %d is %g\n", i, reciprocal(i));
return 0;
}
so we will need to write the implementation of this header file (Source code(.cpp) and header file(.hpp))
First write the header file (reciprocal.hpp):
#ifdef __cplusplusand save it, then open another file which will be the source code (reciprocal.cpp):
extern "C"{
#endif
extern double reciprocal(int i);
#ifdef __cplusplus
}
#endif
#include<cassert>
#include"reciprocal.hpp"
double reciprocal(int i){
assert(i != 0);
return 1.0/i;
}
Now we have three files, Two source files (main.c and reciprocal.cpp) and one header file (reciprocal.hpp) so let's compile them.
First of all notice that reciprocal.hpp is included in both of the source files so we will need to compile it first (Actually we will compile the source file reciprocal.cpp) by this command
g++ -c -I reciprocal.hpp reciprocal.cpp
g++ is the compiler command (For C++)
-c an option to tell the compiler that we need only the object file
-I an option to include the file reciprocal.hpp
Second we will need to compile the main.c file by this command
gcc -c -I reciprocal.hpp main.c
again gcc is the command name (For C)
and the others are the same
Now we need to link the object files to create the executeable file
g++ -o reciprocal main.o reciprocal.o
*Note that we use g++ to compile the files although the main file is a C file , that's it if u have many source files written in both C & C++ then you should use g++
Debugging:
We can see the debugging informaion by invoking the -g option in every command
Copy writes Advanced Linux Programming by Mark Mitchell, Jeffrey Oldham, and Alex Samuel
No comments:
Post a Comment