Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple static library inclusion in CMake TARGET_LINK_LIBRARIES

I have a CMake multiple definition linking problem with an executable that depends on a shared library that contains a static library.

I create a shared library foo that depends on a static library bar.

add_library(foo SHARED foo.cpp)
target_link_libraries(foo bar)

By definition, the content of bar is in library foo.

Then I create an executable exe that depends on foo.

add_executable(exe exe.cpp)
target_link_libraries(exe foo)

At linking time, I have a multiple definition warning/error that tells me that functions in library bar are present twice. When looking at the linking command, I see that exe is linked against bar and foo, which is not consistent.

Do I miss something in the declaration of dependencies? Do I miss a magic CMake keyword?

like image 305
Guillaume Jacquenot Avatar asked Dec 15 '14 18:12

Guillaume Jacquenot


People also ask

How does CMake target_link_libraries work?

target_link_libraries is probably the most useful and confusing command in CMake. It takes a target ( another ) and adds a dependency if a target is given. If no target of that name ( one ) exists, then it adds a link to a library called one on your path (hence the name of the command).

What does add library to CMake?

add_library(<name> <type> IMPORTED [GLOBAL]) Creates an IMPORTED library target called <name> . No rules are generated to build it, and the IMPORTED target property is True . The target name has scope in the directory in which it is created and below, but the GLOBAL option extends visibility.


1 Answers

Like this:

add_library(foo SHARED <foo source files>)
target_link_libraries(foo PRIVATE bar)

If other libraries are linked against foo, make sure to use CMake keywordPRIVATE,PUBLIC or INTERFACE

like image 83
Richard Hodges Avatar answered Oct 18 '22 11:10

Richard Hodges