问题描述
我想包含一些仅适用于 Windows 操作系统的 *.c 和 *.h 文件。但是我无法找到不创建另一个目标的方法,这会导致错误
我想做这样的事情:
add_executable(${TARGET}
main.cpp
mainwindow.cpp
mainwindow.h
mainwindow.ui
if (WIN32)
test.c
test.h
endif()
)
有没有办法做到这一点?
解决方法
您可以为源文件列表使用一个变量,并将与此类似的操作系统特定文件附加到该变量:
set( MY_SOURCES
main.cpp
mainwindow.cpp
mainwindow.h
mainwindow.ui
)
if (WIN32)
SET( MY_SOURCES ${MY_SOURCES}
test.c
test.h
)
endif()
add_executable(${TARGET} ${MY_SOURCES})
,
现代 CMake 解决方案是使用 target_sources
。
# common sources
add_executable(${TARGET}
main.cpp
mainwindow.cpp
mainwindow.h
mainwindow.ui
)
# Stuff only for WIN32
if (WIN32)
target_sources(${TARGET}
PRIVATE test.c
PUBLIC test.h
)
endif()
这应该使您的 CMakeLists.txt
文件比处理变量更容易维护。
除了使用 if
块之外,您还可以使用 generator expression 来约束源:
add_executable(${TARGET} PUBLIC
main.cpp
mainwindow.cpp
mainwindow.h
mainwindow.ui
$<$<PLATFORM_ID:Windows>:
test.c
test.h
>
)
如果您愿意,此方法也适用于 target_sources
命令。