RedHack
RedHack

Reputation: 285

Compiling testing executables with CMake

I am writing a program in C using CLion which in turn uses CMake for its build system. While I like it so far, I've run into the following problem: I want to have two executables, one "normal" which should be build-able for either debug or release, and another that is for testing. The testing executable would include all of my unit tests. To do this, I compiled and installed a library called cmocka which seems to work quite well. However, my main goal is to allow people to build the normal executable with the CMakeLists.txt file without having the testing executable installed. A CMocka installation should only be required if they want to compile the unit tests. That's the part I cannot figure out how to do because no matter what I do, if I want the testing executable to have libcmocka, then I cannot get the normal executable to build without libcmocka.

The following is my CMakeLists.txt file which does work in the sense that it allows me to compile both executables, but it does not accomplish the requirement described above.

cmake_minimum_required(VERSION 3.3)
project(Crypto_Project)

include_directories(/usr/local/include)
find_library(CMOCKA_LIBRARY libcmocka.so.0)

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -lcmocka")

#Normal executable
set(SOURCE_FILES crypto_project.c ap_int.c ap_int.h)
add_executable(Crypto_Project ${SOURCE_FILES})
target_link_libraries(Crypto_Project ${CMOCKA_LIBRARY})

#Testing executable
set(TESTING_SOURCE_FILES ap_int_tests.c ap_int.c ap_int.h)
add_executable(Test_Crypto_Project ${TESTING_SOURCE_FILES})
target_link_libraries(Test_Crypto_Project ${CMOCKA_LIBRARY})

Obviously in order to not compile with cmocka I would need to remove target_link_libraries(Crypto_Project ${CMOCKA_LIBRARY}) from the normal executable as well as compiling without the -lcmocka flag, however, I cannot figure out how to get testing to compile with -lcmocka and the normal executable without it. If I remove target_link_libraries(Crypto_Project ${CMOCKA_LIBRARY}) from the normal executable, it gives me the following error: ~/.CLion12/system/cmake/generated/5c245747/5c245747/Debug/Crypto_Project: error while loading shared libraries: libcmocka.so.0: cannot open shared object file: No such file or directory.

I posted to the CLion forums, but as of yet have not gotten a reply: https://devnet.jetbrains.com/thread/475277?tstart=0 I was hoping someone here may be able to help out.

Thank you in advance.

Upvotes: 0

Views: 1102

Answers (1)

piedar
piedar

Reputation: 2731

Change this line

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -lcmocka")

to this

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99")

CMake should add the -lcmocka flag automatically when you call

target_link_libraries(Test_Crypto_Project ${CMOCKA_LIBRARY})

Upvotes: 1

Related Questions