Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Initialization vs lib.a

  1. Jan 12, 2006 #1

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    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. jcsd
  3. Jan 12, 2006 #2

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Have you tried using -static?

    - Warren
     
  4. Jan 12, 2006 #3

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    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.
     
  5. Jan 12, 2006 #4

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    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
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?