[CMake] Approach to both shared and static lib (again, sorry)

Elvis Stansvik elvis.stansvik at orexplore.com
Sat May 19 09:00:04 EDT 2018


I know this has been asked before, but I've never seen a really
authoritative answer.

Say I have a simple single-library project.

The advise I've seen is to not pass SHARED or STATIC to the
add_library(..), but instead let the user pass
-DBUILD_SHARED_LIBS:BOOL=ON/OFF to build the library as either shared
or static.

That's fine, but leads to packagers having to do ugly things like e.g:

    https://salsa.debian.org/hle/dlib/blob/master/debian/rules

That is, do two separate configure/build/install, in order to get both
a shared and static version. Note that the above was just an example.
But many packagers do it like this.

How can I make life easier for the packager?

I could add a -DFOO_BUILD_SHARED_AND_STATIC_LIBS, and use two
add_library(...), one with SHARED and one with STATIC, but the same
input source files. I could give the two libraries different output
filenames, as to not conflict on e.g. Windows (where I think the .lib
import library containing symbols for the .dll would otherwise
conflict with the static library .lib, or..?).

To not have to repeat the list of sources, I could keep them in a
variable. But that's not recommended in modern CMake AFAIK.

I've also seen people add an object library, and then build the shared
+ static lib from that.

What are your thoughts on all this? How do you go about it? Do you use
the recommended way, with a single add_library(..) and just let
packagers put up with having to do two builds?

Thanks in advance!
Elvis


More information about the CMake mailing list