Reputation: 2022
I'm reading about separate compilation and have a particular question about the process. Suppose I've written a function in a file called function.cpp. Similarly I declared that function properly in a header file function.h. Now a main program, called main.cpp, will use this function. First of all, to produce a working executable would it be enough to run
$ g++ -o main main.cpp
Does this command also compile the function.cpp file or do I have to run first
$ g++ -c function.cpp
$ g++ -o main main.cpp
Now suppose I make some changes in function.cpp. Which file has to be recompiled? Is enough to run
$ g++ -c function.cpp
thanks for your help
Upvotes: 0
Views: 267
Reputation: 5102
You should think about this about two separate tasks:
So back to your question:
$ g++ -c function.cpp
This call to g++ compiles and gets a function.o
$ g++ -o main main.cpp
This call to g++ compiles (main.cpp) and links (main.o and ... You probably need to provide it with al the *.o relevant so that it knows where to look for undefined references).
So if you change function.cpp. You must at least
Upvotes: 2
Reputation: 44364
You can compile both with:
g++ -o main function.cpp main.cpp
I also recommend using -Wall
Upvotes: 0
Reputation: 59811
Using
$ g++ -o main main.cpp
will lead to an undefined reference
linker error, because there is no definition of the symbols defined in function.h
(if they are actually used in main.cpp
).
In the second version you will need to include the object file generated by the first invocation in the second invocation as well.
In the third case, it depends: You will need to recompile main.cpp
if the declaration of function
changed (e.g. a change in the header occurred). Otherwise you just need to link the executable again.
gcc
can generate Make rules when you run it with the -MM
or -M
on a source file. You can use this to generate a primitive Makefile
and you really should use a build system.
Upvotes: 3