Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid recompilation of common object files with CMake?

Tags:

cmake

I've recently added testing through CMake to one of my projects. I've done this by creating another executable that will run my test cases. The tests cases in my project use the code from my main application. Every time I make a change to a source file that is shared between both the main application and the test runner, it recompiles that object twice. Once for the main application and a second time for the test runner.

Is there a way I can share the same object files for both?

My CMakeLists file looks something like this.

AUX_SOURCE_DIRECTORY(${SRC_DIR}/game game_SRC)
AUX_SOURCE_DIRECTORY(${SRC_DIR}/framework/ framework_SRC) 

ADD_EXECUTABLE(${CMAKE_PROJECT_NAME} 
               ${game_SRC} ${framework_SRC})

# --- Testing ---
ENABLE_TESTING()
AUX_SOURCE_DIRECTORY(${TEST_DIR} test_SRC)

ADD_EXECUTABLE(${TEST_RUNNER_NAME}
               ${test_SRC}
               ${framework_SRC} 
)
like image 670
Nexus Avatar asked Dec 12 '22 16:12

Nexus


1 Answers

Yes, by making your framework a separate library. As it is now, you specify the framework_SRCS as sources for your project executable and then you also specify the same sources for the test-runner executable. And CMake simply builds both executables from the specified sources.

Even worse, CMake can not easily assume that the same source file will be used exactly the same for both executables. What if you have a few different compilation flags between your test and your app?

The easiest approach is to link you framework_SRCS into a library and then specify a link-dependency:

ADD_LIBRARY( MyFramework STATIC ${framework_SRCS} )

ADD_EXECUTABLE(${CMAKE_PROJECT_NAME} 
               ${game_SRC})
TARGET_LINK_LIBRARIES( ${CMAKE_PROJECT_NAME} MyFramework )

# --- Testing ---
ENABLE_TESTING()
AUX_SOURCE_DIRECTORY(${TEST_DIR} test_SRC)

ADD_EXECUTABLE(${TEST_RUNNER_NAME}
               ${test_SRC}

TARGET_LINK_LIBRARIES( ${TEST_RUNNER_NAME} MyFramework )

(Note that I explicitly chose to build the library statically. Of course you could opt to leave it up to cmake or enforce a shared build)

Regards, André

like image 133
André Avatar answered Mar 16 '23 19:03

André