Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Basic CMake template for C library with executables and tests
# SPDX-License-Identifier: Unlicense
# Author: Derrick Lyndon Pallas <derrick@pallas.us>
cmake_minimum_required(VERSION 3.1)
cmake_policy(SET CMP0076 NEW)
set(default_build_type "Release")
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "${default_build_type}" CACHE
STRING "Choose the type of build." FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
"Debug" "Release" "MinSizeRel" "RelWithDebInfo")
endif()
set(CMAKE_C_STANDARD 11)
project(projectname)
# objects become the library
set(${PROJECT_NAME}_OBJECTS
)
# headers are installed
set(${PROJECT_NAME}_HEADERS
)
# executables link the shared library and are installed
set(${PROJECT_NAME}_EXECUTABLES
)
# tests link the static library and are not installed
set(${PROJECT_NAME}_TESTS
)
add_library(${PROJECT_NAME} OBJECT)
foreach(object ${${PROJECT_NAME}_OBJECTS})
target_sources(${PROJECT_NAME} PUBLIC ${object}.c)
endforeach(object)
set_property(TARGET ${PROJECT_NAME} PROPERTY POSITION_INDEPENDENT_CODE 1)
add_library(${PROJECT_NAME}-static STATIC $<TARGET_OBJECTS:${PROJECT_NAME}>)
set_target_properties(${PROJECT_NAME}-static PROPERTIES OUTPUT_NAME ${PROJECT_NAME})
add_library(${PROJECT_NAME}-shared SHARED $<TARGET_OBJECTS:${PROJECT_NAME}>)
set_target_properties(${PROJECT_NAME}-shared PROPERTIES OUTPUT_NAME ${PROJECT_NAME} SOVERSION 0 VERSION 0.0.0)
install(TARGETS
${PROJECT_NAME}-static
${PROJECT_NAME}-shared
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib
)
foreach(executable ${${PROJECT_NAME}_EXECUTABLES})
add_executable(${executable} ${executable}.c)
target_link_libraries(${executable} ${PROJECT_NAME}-shared)
install(TARGETS ${executable} RUNTIME DESTINATION bin)
endforeach(executable)
foreach(header ${${PROJECT_NAME}_HEADERS})
install(FILES ${header}.h DESTINATION "include")
endforeach(header)
enable_testing()
add_custom_target(all_tests)
foreach(test ${${PROJECT_NAME}_TESTS})
add_executable(${test} EXCLUDE_FROM_ALL ${test}.c)
target_link_libraries(${test} ${PROJECT_NAME}-static)
add_test(NAME ${test} COMMAND $<TARGET_FILE:${test}>)
add_dependencies(all_tests ${test})
endforeach(test)
build_command(CTEST_CUSTOM_PRE_TEST TARGET all_tests)
string(CONFIGURE \"@CTEST_CUSTOM_PRE_TEST@\" CTEST_CUSTOM_PRE_TEST_QUOTED ESCAPE_QUOTES)
file(WRITE "${CMAKE_BINARY_DIR}/CTestCustom.cmake" "set(CTEST_CUSTOM_PRE_TEST ${CTEST_CUSTOM_PRE_TEST_QUOTED})" "\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment