How do I * prevent * loose linking of static library symbols in Visual C ++?

As for my practical tests, when linking a static library ( .lib

) to your executable in Visual C ++ , if any .obj executable defines a duplicate symbol by one in the static library, the symbol in the static library will be ignored.

Confirm (Feb 18 '10 at 17:46 Michael Burr) :

MSVC is used to behaving so that if a symbol is defined in the .obj and .lib file it will use the file in the .obj file without warning. I recall that it will also handle the situation where a symbol is defined in multiple libraries, it will use the one in the library with the name first in the list.

I can't say that I've tried this after a while, but I would be surprised if they change this behavior (especially that .obj certain symbols override symbols in .lib files).

A quick test with VS 2010 RC indicates that the behavior I described still exists.

( "Windows Static Library with Default Functions" also seems like a confirmation to me)


Now, first of all, I'd like to be proven wrong, but at least for a regular C ++ function, it seems to be the case.

Second, is there a way to prevent this? I have a function that, when there are any binary references to a static library that contains that function, I would like to confirm that the version from the static library is actually being used, and not some rest or something else in another project. (Note: Fn in the question test_suite* init_unit_test_suite(int argc, char* argv[])

is (*), so I can't practically change it because it's from a third party lib.)


(*): This is the main function of Boost.Test that should be provided by our custom static lib. If any developer creates a Unit Test project that is automatically linked to a static lib automatically via the property sheet, but mistakenly defines a function as well, the build should abort instead of using the function provided by dev.

+3


source to share


1 answer


I think the linker behaves differently if you reference an independent obj file rather than a static lib. At the very least, you should get a duplicate characters warning / error.



When I needed something like this , I couldn't find it in the MS toolchain either , but there are two MS devices that come close and can be handy: __ declspec (selectany) and the undocumented # pragma / alternatename . Perhaps binding to an obj file and declaring the symbol as selectany would do the trick? If not, perhaps adding a #pragma (linker, "/ alternatename: _YourSymbol = _DefaultExeSymbol") comment to the exe-obj file will do it.

0


source







All Articles