Say your program is composed of two source files (main.c and auxiliary.c) and two header files (declarations.h and auxiliary.h).
Then you run the compiler as follows:
$gcc main.c auxiliary.c -o myprogram
Question 1: Will the compiler create one single object file for my program (i.e., just the libraries are missing) or will it create two object files, one for each source file (and then link everything together)?
Question 2: Is there ever the need to call the linker separately? Because if you use the command above the compiler will take care of that for you, right?
Question 3: Why some libraries get linked automatically (e.g., stdio) and why some require extra work (e.g., math.h requires adding a -lm when compiling). What does the -lm stand for?
Question 4: Suppose you have a single source file and your program doesn’t need any external library. Does this mean that the object code you would get from the compiler would be executable already? (i.e., compiling it like $gcc -c main.c).
gcccreates one object file per source file, then links them to build the executable.Your example proves that
gccis able to chain all needed stepsThe library that gets automatically linked is the standard C library. The others need to be specified. This allows to build a smaller executable when you don’t need
atan2().-lmindicates to the compiler that it should find the math library, whose id ism. On Unix, its filename islibm.soorlibm.adepending whether the link is dynamic (performed at runtime and leading to a smaller executable) or static (performed at link time and leading to a standalone executable).No. It must be linked to the standard C library anyway. Moreover, the file format of an object code is different than an executable.