math
math

Reputation: 2022

Separate compilation and linking again

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

Answers (3)

jsantander
jsantander

Reputation: 5102

You should think about this about two separate tasks:

  1. Compiling. This provides a *.o, this contains all the function/classes/methods/etc. that are defined in *.C file and the *.h included from it (defined, not just declared). For those things that have been declared, but not defined, there will be just a reference ("here's something I don't know")
  2. Linking. This gets together all the *.o (and *.a and *.so or *dll if you have libraries to throw into the mix) and will try to match all undefined references with a definition in other *.o

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

  1. compile it to get a function.o
  2. link the main program again so that the new definitions in function.cpp gets linked to the undefined references in the rest of the program.

Upvotes: 2

cdarke
cdarke

Reputation: 44364

You can compile both with:

g++ -o main function.cpp main.cpp

I also recommend using -Wall

Upvotes: 0

pmr
pmr

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

Related Questions