# Initialization vs lib.a

1. Jan 12, 2006

### Hurkyl

Staff Emeritus
Here's my (UNIX) situation.

I have three object files:

program.o
public.o
private.o

public.o is "standalone" -- it is entirely self-contained.

program.o refers to functions defined in public.o

private.o is "hidden" -- neither program.o nor private.o make any reference to anything contained in private.o. However, private.o contains some static initialization that calls functions in public.o. (Essentially registering itself with the features that public.o provides)

Linking them together is no problem. I simply do:

g++ program.o public.o private.o

and a.out does exactly what I expect it to do.

Then, I tried a variation. I put public.o and private.o into a library. I think the command was

ar crsu libtest.a public.o private.o

Now, I link program.o with this library

g++ program.o -L. -ltest

This doesn't work, because private.o's startup code is never executed.

I also tried

g++ program.o libtest.a

and got the same result.

Can I do anything to have this all behave like I want? (But without having program.o or public.o reference anything in private.o?)

2. Jan 12, 2006

### chroot

Staff Emeritus
Have you tried using -static?

- Warren

3. Jan 12, 2006

### Hurkyl

Staff Emeritus
I'm not familiar with that option. I can look it up in the man page, if you don't want to explain it further.

4. Jan 12, 2006

### chroot

Staff Emeritus
Static linking means you want to include the library's code inside your executable. The alternative is dynamic linking, where you leave the code in the library, and reference it only at runtime. I suspect that if you don't compile your library statically into your executable, the static initialization code never has any reason to be called.

Try g++ -static program.o libtest.a and let me know what it does.

- Warren