【问题标题】:How to make CMakelists.txt to include some *.c and *.h files only for one OS?如何使 CMakelists.txt 仅包含一个操作系统的 *.c 和 *.h 文件?
【发布时间】:2021-07-27 23:23:04
【问题描述】:

我想包含一些仅适用于 Windows 操作系统的 *.c 和 *.h 文件。但是我找不到不创建另一个目标的方法,这会导致错误

我想做这样的事情:

add_executable(${TARGET}
     main.cpp
     mainwindow.cpp
     mainwindow.h
     mainwindow.ui
if (WIN32)
     test.c
     test.h
endif()
)

有没有办法做到这一点?

【问题讨论】:

  • 使用变量并设置
  • 这能回答你的问题吗? OS specific instructions in CMAKE: How to?
  • 顺便说一句,我从标签中删除了Qt,因为我认为这对问题或解决方案并不重要。使用或不使用Qt 框架都是一样的。

标签: c++ c cmake cmakelists-options


【解决方案1】:

现代 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 文件比争论变量更容易维护。

【讨论】:

  • 谢谢。我倾向于仍然使用我在 2008 年开始使用 CMake 时学到的许多技术。下次我使用这种技术时必须记住这一点,在我的情况下,我不时希望有条件地包含源文件和工厂.
  • @drescherjm - 直到几年前我都在同一条船上。这肯定是一种思想转变,但是一旦我愿意喝 kool-aid,我发现它比传统风格干净得多 :)
【解决方案2】:

您可以为源文件列表使用一个变量,并将类似于以下的操作系统特定文件附加到该变量:

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})

【讨论】:

    【解决方案3】:

    除了使用if 块之外,您还可以使用generator expression 约束源:

    add_executable(${TARGET} PUBLIC
       main.cpp
       mainwindow.cpp
       mainwindow.h
       mainwindow.ui
       $<$<PLATFORM_ID:Windows>:
           test.c
           test.h
      >
    )
    

    如果您愿意,此方法也适用于 target_sources 命令。

    【讨论】:

      猜你喜欢
      • 2014-11-26
      • 2022-11-30
      • 2018-04-05
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      相关资源
      最近更新 更多