tags:

views:

90

answers:

2

I'm reading about how to put a makefile together, but no-one seems to mention what to do if your files require different sets of libraries, they all seem to use the same set of libraries for each file. Since it seems unlikely that every single file has the same libraries, I take it the list they use must amalgamate all of the libraries required across the project.

I just wanted to know if there's any downside to including too many libraries, or if the compiler works out which ones are needed and ignores the rest?

Thanks

+1  A: 

The linker (the tool that takes all the .o files created from compiling your source code and turns them into an executable) won't link in code that wasn't called into the executable. I.e. simply stated:

void foo()
{
 // code
}

void bar()
{
 // code
}

int main()
{
    foo();
    return 0;
}

Here the code of foo will be linked into the executable, and the code of bar will not. Assuming this is the whole program, of course.

For a somewhat fuller explanation, read the answer I've given just an hour ago to another question.

Eli Bendersky
Linker is pretty smart at this sort of thing.
zdav
+2  A: 

If there's any downside to including too many libraries?

Hardly any.

If the compiler works out which ones are needed and ignores the rest?

Almost exactly right: it's the linker that examines each library and pulls only the object code that it needs.

The one downside to including a very large number of libraries is that it can be hard to get them in the right order. Recent versions of the GNU linker have some special options that can help with the libraries-out-of-order problem (and it's about time too), but such options remain nonportable. On the other hand, if you include libraries that aren't actually needed, it's not going to matter what order they appear in, because the linker will carefully examine each one and decide that none of its contents are needed.

For all those people out there who are looking for projects, here's one I'd love to have: give me a tool that takes a list of libraries and does a topological sort on the interlibrary dependencies, then tells me an order I can put them on the command line so that there are no gratuitously undefined symbols.

Norman Ramsey
Thanks, that's helpful. One thing, though - I've never come across anything regarding library order. Is this something I should be particularly concerned about? If so, how do I go about determining the correct order library inclusions?
wyatt
@wyatt, if order hasn't bitten you, there's no need to worry about it. Otherwise the only rule is that if liba depends on libb the command line must have `-la -lb` and not `-lb -la`.
Norman Ramsey