I just have a quick question as I'm trying to understand how to compile (in ubuntu 12.04) a main in c++ that includes a simple header file.
The command:
g++ -o main main.cpp add.cpp -Wall
Works fine. However, that confuses me about the point of the header file. At the moment, I have the simple program:
#include <iostream>
#include "add.h"
using namespace std;
int main () {
int a, b;
cout << "Enter two numbers to add together" << endl;
cin >> a >> b;
cout << "Sum of " << a << " and " << b << " is " << add(a,b) << endl;
return 0;
}
Where my "add.cpp" is simply adding the two numbers together.
Is the header file simply a replacement for the function prototype? Do I need to compile the header file separately or is it sufficient to include all of the .cpp files in the command line? I understand that if I need more files a makefile would be necessary.
Best Solution
The
#include
preprocessor code just replaces the#include
line with the content of the corresponding file, which isadd.h
in your code. You can see the code after preprocessing with g++ argument-E
.You can put theoretically anything in the header file, and the content of that file will be copied with a
#include
statement, without the need to compiling the header file separately.You can put all the
cpp
file in one command, or you can compile them separately and link them in the end:EDIT
you can also write function prototypes direct in cpp file like (with NO header file):
It also works. But using header files is preferred since prototypes might be used in multiple cpp files, without the need of changing every cpp file when the prototype is changed.