views:

60

answers:

3

In a c++ project I am working on, I have a simple c++ file that needs to run some code at the beginning of the program execution. This file is linked into a static library, which is then linked into the main program.

I have similar code in other files running fine, that looks something like:

bool ____nonexistent_value = executeAction();

However, it does not work inside this file unless I make use of a function implemented in this file. It does work if the library is compiled as a shared library. I'd prefer to link this statically as the library is only a convenience as the file is in a different directory.

Update (Solution):

For now creating shared instead of static libraries makes everything work. Later I will look into getting everything linking with static libraries. Thanks for everyone's help!

+1  A: 

I'm not sure if there's a way to guarantee such static allocation in a static library, but you can always make it explicit. Provide an init function for your library that will be called from main to setup everything you need. This way you don't have to worry about linkers omitting code that's apparently unused, etc.

Mark B
Thank you for the response! The code I am trying to have executed is meant to register objects inside the main program. The static libraries are like libtool's helper libraries. I was mainly looking for a way to call an object specific function inside the source file for the object. It appears I will have to come up with a different solution anyways.
MJD
+1  A: 

If no symbol is referenced in that particular file then the file will not be included by the linker. You have two options:

  1. Remove the file from library and include it (object or source file) directly in the command line for compilation/linking. Then the file should be included in executable.
  2. Have a symbol in a file which you reference from from other files (for example the one with main() definition), this should "pull" the file during linking.
Tomek
Thank you for the answer! I had a feeling this was the issue, thank you for confirming!
MJD
A: 

There's no guaranteed order for static initialization. You want to be very careful with this!

Jay
Thank you for responding! I understand there is no order, the code in I'm using merely registers objects into an object factory (based on some identifier). The order does not matter in this.
MJD