Peter
Peter

Reputation: 1687

CMake link single class in another project

its one of my first c++ projects and i got problems with CMake.

I have MyProject with an executeable and i got a Project tests with boost unit tests. I tried it the following way, but i failed. Obviously i cant have two executeables this way and i dont know how to fix fix it.

This is the CMake of MyProject

project (MyProject)
find_package( Boost 1.48.0  COMPONENTS thread )
set(MYPROJECT_SRCS main.cpp foo.h foo.cpp)
add_executable(MyProject ${MYPROJECT_SRCS})
target_link_libraries(MyProject  ${Boost_LIBRARIES})

This is the CMake of tests

project (tests)
find_package( Boost 1.48.0 COMPONENTS thread unit_test_framework) 
find_package( Boost 1.48.0  COMPONENTS thread )
include_directories("../MyProject")
set(TEST_SRCS test.cpp )
add_executable(tests ${TEST_SRCS})
target_link_libraries(tests ${Boost_LIBRARIES} MyProject)
add_test( example_test tests )

CMake Error at tests/CMakeLists.txt:13 (target_link_libraries):
Target "MyProject" of type EXECUTABLE may not be linked into another
target. One may link only to STATIC or SHARED libraries, or to executables with the ENABLE_EXPORTS property set.

I tried to "ENABLE_EXPORTS property set", but i think i did it wrong.

Upvotes: 4

Views: 7650

Answers (2)

Andrey
Andrey

Reputation: 925

There are several modifications to be done in MyProject project (the one you are referencing).

  1. CMakeList.txt file has to include a ENABLE_EXPORTS property:

    add_executable(MyProject foo.c)
    set_property(TARGET MyProject PROPERTY ENABLE_EXPORTS 1)

    This property reacts differently depending on OS. With Windows OS it will create a .lib file aside a regular .exe file.

  2. External signatures have to be exported:

    #define EXPORTED_API __declspec(dllexport)

    class EXPORTED_API MyProject {...}
    or
    int EXPORTED_API func() {...}

Upvotes: 2

Gluttton
Gluttton

Reputation: 5958

You shouldn't link your executable file with tests, instead you need include source files of your main project in tests source list:

set(TEST_SRCS test.cpp ../MyProject/foo.cpp)

target_link_libraries(tests ${Boost_LIBRARIES} )

P.S. Also it will be useful when you want to analyze test coverage.

Upvotes: 5

Related Questions