Eloff
Eloff

Reputation: 21656

CMake how to configure this C++ project?

I want a cmake project with two configurations BUILD and TEST.

BUILD compiles all sources not in test subdirectory into a shared library. TEST compiles all sources, including those in test subdirectory (which includes main.cpp) into an executable that runs the tests. I don't want TEST to build the shared library. I don't want BUILD to build the test executable.

I currently have it on disk as:

project/
  test/
    test_foo.cpp
    main.cpp

  bar.hpp
  widget.hpp
  bar.cpp
  widget.cpp
  ...

I can move things around if it makes it easier. What do I put in my CMakeLists.txt files?

Upvotes: 1

Views: 952

Answers (1)

user3288829
user3288829

Reputation: 1275

It looks to me like you want to use cmake's OPTION command. Pick one configuration to be on by default (or neither if you want to force the person compiling the code to choose)

OPTION( BUILD_SHARED_LIBRARY "Compile sources into shared library" ON )
OPTION( RUN_TESTS "Compile test executable and run it" OFF )

You'll want to make sure that the options are mutually exclusive, and error out otherwise

if ( BUILD_SHARED_LIBRARY AND RUN_TESTS )
  message(FATAL_ERROR "Can't build shared library and run tests at same time")
endif()

You can then put the rest of your commands inside if blocks based on those variables

if ( BUILD_SHARED_LIBRARY )
  #add subdirectories except for test, add sources to static library, etc
endif()

if ( RUN_TESTS )
  #compile an executable and run it, etc.
endif()

Upvotes: 5

Related Questions