[CMake] Using cmake to build a static library

Michael Wild themiwi at gmail.com
Thu Sep 15 03:12:41 EDT 2011


On 09/15/2011 08:49 AM, Denis Carniel wrote:
> Hi,
> 
> I came across cmake few weeks ago as a very interesting way to build
> projects for multiple platforms. It allows us at work to use a common
> code base for multiple platforms without actual duplication which is
> really neat.
> 
> Though we're facing an issue related to the fact cmake isn't the only
> tool involved in our build process. We have split our code between
> the core logic which is compiled in C++ for multiple platforms
> (windows x86 and x86_64, Mac OSX and in the future linux) then based
> on that core logic we would like to produce SDKs for each platform
> using their specific features (for easier integration in projects).
> 
> The problem is the following: The core logic is meant to be a static
> library (.lib on windows, .a on Mac / Linux) and then another project
> should pick up that library and include it into an executable. That
> final project is (a) not linked with the original cmake project (b)
> potentially not even built by cmake. For those reasons we'd like that
> the generated static library include its own dependencies in order to
> avoid dragging a long list of dependencies, unfortunately that does
> not seem to be be case in the current state of things.
> 
> If I set the type of my output to "SHARED" (through the "ADD_LIBRARY"
> command), I see all dependencies appear in the Visual Studio project
> and the produced DLL seems correct. Though if the type is set to
> "STATIC" (the one we want), the dependencies are simply not passed to
> the Visual Studio project (AdditionalDependencies &
> AdditionalLibraryDirectories are not set for VCLibrarianTool).
> 
> Hence my overall question: How can I have cmake produce a static
> library in which dependencies are linked ?
> 
> Thanks in advance for your help. Denis
> 
> PS: I know DLLs work on windows but those are not an option, because
> of deployment constraints we need to produce a single executable file
> in the end.

Well, static libraries just don't give you that. They are essentially
glorified archive files (think "zip-file") containing the object files.
When you do a TARGET_LINK_LIBRARIES(myStaticLib someOtherLib), CMake
remembers that dependency internally and will add someOtherLib to all
the link-lines where myStaticLib is used, but it can't possibly embed
that information into the static library.

If your downstream projects are CMake, you can tell CMake to "export"
the myStaticLib target along with its dependencies to a special file
which then can be imported by the downstream project. If it isn't, on
Linux Mac and other Unix-ish platforms (MinGW, Cygwin, etc.) you would
write a pkg-config file which contains that information. With pure MSVC
I don't think that this is possible, so IMHO you'll have to add the
dependencies manually.

Michael


More information about the CMake mailing list