CMake中add_custom_target使用困惑:执行cmake未输出预期消息
Hey there! Let's break down why your custom target isn't showing the message you expected, and fix it step by step.
First, let's clear up a key CMake concept: CMake has two distinct phases—the configuration phase (when you run cmake .. or similar to generate build files) and the build phase (when you run make, ninja, or build via your IDE).
Your current code has two small issues:
- You used
message("SomeMessage")directly as a COMMAND inadd_custom_target. Themessage()function is a CMake script command, not a system shell command. When the build phase runs, it'll try to executemessageas a system command (which doesn't exist on most systems), so nothing gets output. add_custom_targetruns its commands during the build phase, not the configuration phase. So even if the command was correct, you wouldn't see the message when runningcmake—you'd only see it when you actually build the target.
Fix 1: Show the message during the build phase
To properly output a message in the build phase, use CMake's built-in echo utility via ${CMAKE_COMMAND} -E echo. Here's the corrected code:
add_custom_target(myTarget ALL COMMAND ${CMAKE_COMMAND} -E echo "SomeMessage" )
After generating your build files with cmake, run your build command (like make or ninja)—you'll see "SomeMessage" printed during the build process.
Fix 2: Show the message during the configuration phase
If your goal was to print the message when running cmake (configuration phase), you don't need add_custom_target at all. Just use the message() function directly:
message("SomeMessage")
This will output the message immediately when you run the cmake command.
Quick Recap
- Use
message()alone for configuration-phase messages. - Use
${CMAKE_COMMAND} -E echoinsideadd_custom_targetfor build-phase messages, and remember to run your build tool to trigger it.
内容的提问来源于stack exchange,提问作者Cantaff0rd

