How to Resolve Static Libraries Losing Object File References On EXE Link  
Author Message
glavian





PostPosted: Visual C++ General, How to Resolve Static Libraries Losing Object File References On EXE Link Top

I have a project that is an executable linked to another project that has a static object. The static object does not get initialized unless I reference a function or variable in the file the static object exists. I understand why this is but am looking for a way to force linkage to the object without declaring a usage of the object from the main .exe. Are there any #pragmas that could do this

 

In the following example the constructor doesn't get called. If I add a local variable of TestClass to main the static variable will invoke the constructor. I would like a way to force linkage with the TestProject2.obj file without having to add it to project settings because in my code base we're using macros to declare the static variables and would like to find a way to force the linkage through the macro.

Test Project(exe) - links to TestProject2

#include "TestProject2.h"

main()

{

return 0;

}

 

TestProject2(lib)

TestProject2.h

#pragma once

class TestClass

{

public:

    TestClass(int inNum);

    static TestClass sClass;

    int mInt;

};

 

TestProject2.cpp

 

TestClass   TestClass::sClass(5)

TestClass::TestClass(int inNum)

{

  mInt = inNum; 

}

 

 

 



Visual C++10  
 
 
Viorel.





PostPosted: Visual C++ General, How to Resolve Static Libraries Losing Object File References On EXE Link Top

I think this issue is already reported at the following links:

It seems the linker can be forced to keep your data if the executable calls some function from the static library.

 

Therefore, I would suggest adding and calling of a dummy function, as was shown in the sibling thread:

// static library:

 

int DummyFunction()

{

    return 0;
}

In order to call this function automatically from executables, you can try adding of these lines to the header file provided by static library and used in the executables:

// header file of static library:

 

extern int DummyFunction();

static int unused = DummyFunction();

I hope this helps.


 
 
glavian





PostPosted: Visual C++ General, How to Resolve Static Libraries Losing Object File References On EXE Link Top

Thanks it does help but I'm trying to avoid having the executable force the linkage. One alternative I came up with was to add all the definitions to 1 .cpp file and link in that .obj specifically which works pretty well, but I would rather find a way to do it in each individual .cpp file. Without forcing an .obj reference in the linker to all the files.