如何让 CMakelists.txt 包含一些仅适用于一个操作系统的 *.c 和 *.h 文件?

问题描述

我想包含一些仅适用于 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 命令。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...