What happens if more than one .cpp file is included?

Becase I've seen (and used) situations like this:

In header.h:

class point
{
public:
    point(xpos, ypos);
    int x;
    int y;
};

      

In def.cpp:

#include"header.h"
point::point(xpos, ypos)
{
    x = xpos;
    y = ypos;
}

      

In main.cpp:

#include"header.h"
int main()
{
    point p1(5,6);
    return 0;
}

      

I know the program is executed from main, but how does the compiler know which order to compile the .cpp files? (In particular, if you have multiple non-networked .cpp files).

+1


a source to share


7 replies


the compiler doesn't matter - it compiles each .cpp file to an .obj file, and the .obj files contain a list of missing characters. So, in this case, main.obj says "I'm missing point::point

".



The linker is then executed to take all the .obj files, concatenate them into an executable file, and ensure that each .obj file is missing from one of the other .obj files - hence the term "linker".

+10


a source


If you include them in two different cpp files, this is not a problem. If you include the same header twice, you get errors for duplicate definitions.

You have to use the included guards to get around this.

At the top of the file, before any code:



#ifndef HEADER_H_ //every header gets it own name
#define HEADER_H_

      

Down below:

#endif

      

+4


a source


The compilation order does not matter. Everything is compiled by a compiler that uses .h files to make sure the symbols you are using are at least declared. It is the job of the linker after the compiler has finished to actually match your method calls to their implementations.

+1


a source


The compiler does not need to know which order to compile the .cpp files.

The linker sorts all the compiled .o files (build from.cpp) and resolves everything into one executable file.

+1


a source


Usually you compile them yourself (or with a build tool like make

). The header file allows you to compile them in any order. If you compile them together, the order is probably the order you pass to the compiler command, but it doesn't really matter, they all end up linked to the same executable.

0


a source


This is a sample Graph Theory app. Compiled modules contain relative offsets for all blocks of code and its up to the linker to determine the dependencies (graph) when it creates the executable.

0


a source


This is why you see #ifndef HEADER_H and #define HEADER_H at the top of some header files. The concept of only one inclusion of each header file as described here , for example.

-1


a source







All Articles