Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get CMake to declare a target phony

I want to generate some compile time constants. The first answer to another question gets me quite close. From my CMakeLists.txt:

add_library(${PROJECT_NAME} STATIC ${CXX_SRCS} compile_time.hpp)
add_custom_command(OUTPUT compile_time.hpp
    COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_SOURCE_DIR}/compile_time.cmake)

This works in the sense that the first time I run make, it generates compile_time.hpp, so that the values of the variables are defined when I run make and not cmake. But compile_time.hpp is not remade when I rerun make or even cmake to redo the makefiles.

How can I make the target compile_time.cpp be marked as phony so that it is always remade? I tried

add_custom_target(compile_time.hpp)

to no effect.

like image 311
pythonic metaphor Avatar asked Jun 28 '16 14:06

pythonic metaphor


People also ask

How do I add a target in CMake?

Adds a target with the given name that executes the given commands. The target has no output file and is always considered out of date even if the commands try to create a file with the name of the target. Use the add_custom_command() command to generate a file with dependencies.

What is .phony all in Makefile?

PHONY: allows to declare phony targets, so that make will not check them as actual file names: it will work all the time even if such files still exist. You can put several . PHONY: in your Makefile : .

What are CMake targets?

A CMake-based buildsystem is organized as a set of high-level logical targets. Each target corresponds to an executable or library, or is a custom target containing custom commands.

What is CMake build?

CMake is a cross-platform build system generator. Projects specify their build process with platform-independent CMake listfiles included in each directory of a source tree with the name CMakeLists. txt. Users build a project by using CMake to generate a build system for a native tool on their platform.


1 Answers

add_custom_target creates a "phony" target: It has no output and is always built. For make some target depended from the "phony" one, use add_dependencies() call:

add_custom_target(compile_time
    COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_SOURCE_DIR}/compile_time.cmake
)
# Because we use *target-level* dependency, there is no needs in specifying
# header file for 'add_library()' call.
add_library(${PROJECT_NAME} STATIC ${CXX_SRCS})
add_dependencies(${PROJECT_NAME} compile_time)

Library's dependency from the header compile_time.h will be detected automatically by headers scanning. Because script compile_time.cmake updates this header unconditionally, the library will be rebuilt every time.

like image 121
Tsyvarev Avatar answered Sep 30 '22 13:09

Tsyvarev