views:

344

answers:

1

Same source, all that, just want a static and shared version both. Easy to do?

+3  A: 

Yes, it's moderately easy. Just use two "add_library" commands:

add_library(MyLib SHARED source1.c source2.c)
add_library(MyLibStatic STATIC source1.c source2.c)

Even if you have many source files, you would place the list of sources in a cmake variable, so it's still easy to do.

On Windows you should probably give each library a different name, since there is a ".lib" file for both shared and static. But on Linux and Mac you can even give both libraries the same name (e.g. libMyLib.a and libMyLib.so):

set_target_properties(MyLibStatic PROPERTIES OUTPUT_NAME MyLib)

But I don't recommend giving both the static and dynamic versions of the library the same name. I prefer to use different names because that makes it easier to choose static vs. dynamic linkage on the compile line for tools that link to the library. Usually I choose names like libMyLib.so (shared) and libMyLib_static.a (static). (Those would be the names on linux.)

Christopher Bruns
Was hoping for them to have the same name, but oh well. Another question: Can you tell CMake to link static libraries into the shared library when possible?
gct
More about "same name": If you are on Windows and want the same name for both libraries and you don't need the shared .lib file, it is possible to create a static .lib and a shared .dll. But you need that shared .lib file if you are using your library for ordinary compile time linking.
Christopher Bruns
I'm not sure I understand your question about linking static libraries into the shared library.
Christopher Bruns
Example: I have libsomelib that libmylib.so depends on, I'd like it to use libsomelib.a and merge it into libmylib.so where possible...
gct
Either you link libmylib.so with libsomelib.a, in which case libmylib.so will include libsomelib.a, or you don't. There is no "where possible". (Remember that static libraries are just collections of object files.)
JesperE