views:

756

answers:

3

I was trying to do something like this in a makefile:

program.exe: ui.o main.o
   gcc ......etc
ui.o: window1.o window2.o
   gcc -c window1.o window2.o -o ui.o #this doesn't want to work
window1.o: window1.c window1.h window1_events.c window1_controls.c ...
   gcc -c window1.c window1_events.c window1_controls.c... -o window1.o
window2.o: ...
   gcc ...
main.o: ...
   gcc ...

but when I compile like this, it gives the error "input file unused because linking not done," and then I get a bunch of unresolved externs, etc--problems which are resolved by changing

program.exe: ui.o main.o
   gcc ...

to

program.exe: window1.o window2.o main.o
   gcc ...

so is it possible to just link object files together, to avoid having mile-long lines in a makefile and break down the build process a little more?

+4  A: 

I bunch of object files is a library. You can create a library with the ar utility. The following example creates a library called mylib.a containing the files foo.o and bar.o

ar rvs mylib.a foo.o bar.o

You can then link with it by using it on the compiler command line:

gcc -o myexe main.c mylib.a
anon
+3  A: 

To create a library:

ar rvs somelib.a file1.o file2.o file3.o

To link it:

gcc -o program.exe file4.o somelib.a
PaV
+3  A: 

Yes: to merge several object files into one, use ld -r or ld -Ur:

From "man ld" on Linux:

   -r
   --relocatable
      Generate  relocatable  output---i.e.,  generate  an output file that can
      in turn serve as input to ld.  This is often called partial linking.
      As a side effect, in environments that support standard Unix magic
      numbers, this option also sets the output file’s magic number to
      "OMAGIC".
      If this option is not specified, an absolute file is produced.
      When linking C++ programs, this option will not resolve references to
      constructors;  to do that, use -Ur.

You could also do this with gcc:

gcc -Wl,-r foo.o bar.o -o foobar.o -nostdlib

Merging object files like this has some advantages over using an archive library: if merged files change very infrequently (compared to say main.c), your final executable links will be faster.

OTOH, with archived library, the linker will only use what it needs, so your executable may end up being smaller if e.g. window2.c ends up not being necessary.

Employed Russian