Wednesday, August 29, 2007

Linking to C++/CLI Static Libraries

So I had this weird problem where I was building a C++/CLI static library that included managed and unmanaged code. I had an unmanaged class that called static functions from a managed class (this is known as mixed mode) and was compiling the whole thing with /clr. When I was building another mixed mode .dll that called the mixed static library, I was getting linker errors to the functions in the static lib's managed classes. I found this on microsoft.public.dotnet.general newsgroup:


Hi all,

I have a .NET solution with several projects in it. One project is a "utilities" project that is compiled into a static library. It contains managed and unmanaged C++ in several files. So I am compiling using managed extensions. This project compiles successfully.

Another project in the solution, BrassControls, is dependent on the Utilities project. It uses several of the classes in Utilities. However, it fails at linking. I get the following error when building the BrassControls project [ -- the class BrassVersion is in the Utilities project]:

LINK : error LNK2020: unresolved token (06000050) Brass.BrassVersion::.ctor
LINK : error LNK2020: unresolved token (06000051) Brass.BrassVersion::.ctor
LINK : error LNK2020: unresolved token (06000052) Brass.BrassVersion::Finalize
LINK : error LNK2020: unresolved token (06000053) Brass.BrassVersion::ToString

These relate to the functions in the Brass::BrassVersion class. This is the only class in the Utilities project that is a __gc class.

I have verified that the project dependencies are set so that BrassControls is dependent on Utilities. But for some reason it can't "see" the tokens associated with BrassVersion.

Both projects are compiled using managed extensions. Both are using the same run-time library.

Can anyone help me figure this out?
Thanks,
Matt.


Ah-ha! This was exactly my problem. Unfortunately, the newsgroup didn't have an answer and it took me a few more hours to find it. The answer is easy... on the .dll that includes the static library, make sure the Linker option for the .dll "Use Dependency Inputs" is set to "Yes". I guess for unmanaged classes it would include them, but for managed classes it wouldn't, so I was getting a linker error (LNK2020) for unresolved tokens. It took me forever to figure this out and really pissed me off. I found the answer here.

No comments: