CMake中#cmakedefine替换结果不一致的原因咨询
The core issue here is how CMake's #cmakedefine directive works in your config.h.in file. Let's break down exactly what's happening:
When you use #cmakedefine VAR_NAME ... in your template, CMake checks the CMake variable named VAR_NAME (not the value you're inserting with @...@). Here's the play-by-play for your lines:
First line:
#cmakedefine HAVE_GETOPT @HAVE_GETOPT@- CMake looks for the CMake variable
HAVE_GETOPT, which you set viacheck_function_exists(getopt HAVE_GETOPT). Since it evaluates to true (1), this line becomes#define HAVE_GETOPT 1as expected.
- CMake looks for the CMake variable
Second line:
#cmakedefine STDLIB_HAS_GETOPT @HAVE_GETOPT@- CMake now checks for the CMake variable
STDLIB_HAS_GETOPT—but you never set this variable in yourCMakeLists.txt! Even though you're inserting@HAVE_GETOPT@as the value, the#cmakedefinedirective depends entirely on the variable name immediately after it. SinceSTDLIB_HAS_GETOPTisn't defined in CMake, it defaults to false, resulting in/* #undef STDLIB_HAS_GETOPT */.
- CMake now checks for the CMake variable
How to fix it
You have two straightforward options to get the expected output:
Option 1: Set STDLIB_HAS_GETOPT in CMakeLists.txt
Add this line right after your check_function_exists call:
set(STDLIB_HAS_GETOPT ${HAVE_GETOPT})
This copies the value of HAVE_GETOPT into STDLIB_HAS_GETOPT. Now when CMake processes the second #cmakedefine line, it will see STDLIB_HAS_GETOPT is true and generate #define STDLIB_HAS_GETOPT 1.
Option 2: Use a preprocessor conditional instead of #cmakedefine
If you don't want to add another variable to your CMake config, replace the second #cmakedefine line in config.h.in with:
#if @HAVE_GETOPT@ #define STDLIB_HAS_GETOPT @HAVE_GETOPT@ #endif
This will define STDLIB_HAS_GETOPT only when HAVE_GETOPT is true, and leave it undefined otherwise—exactly matching the behavior you want.
Either approach will produce your desired output:
#define HAVE_GETOPT 1 #define STDLIB_HAS_GETOPT 1
内容的提问来源于stack exchange,提问作者einpoklum

