C++ – Compiling with g++ – including header files

c++g++header

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 is add.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:

g++ -c source1.cpp -o source1.o
g++ -c source2.cpp -o source2.o
g++ -c source3.cpp -o source3.o
g++ source1.o source2.o source3.o -o source

EDIT

you can also write function prototypes direct in cpp file like (with NO header file):

/* add.cpp */
int add(int x, int y) {
    return x + y;
}
/* main.cpp */
#include <iostream>
using namespace std;

int add(int x, int y);    // write function protype DIRECTLY!
// prototype tells a compiler that we have a function called add that takes two int as
// parameters, but implemented somewhere else.

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;
}

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.