Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何使CMakelists.txt仅为一个操作系统包含一些*.c和*.h文件?_C++_C_Cmake_Cmakelists Options - Fatal编程技术网

C++ 如何使CMakelists.txt仅为一个操作系统包含一些*.c和*.h文件?

C++ 如何使CMakelists.txt仅为一个操作系统包含一些*.c和*.h文件?,c++,c,cmake,cmakelists-options,C++,C,Cmake,Cmakelists Options,我只想包含一些适用于Windows操作系统的*.c和*.h文件。但是我找不到在不创造另一个目标的情况下如何做到这一点的方法,这意味着一个错误 我想这样做: add_executable(${TARGET} main.cpp mainwindow.cpp mainwindow.h mainwindow.ui if (WIN32) test.c test.h endif() ) 有什么方法可以做到这一点吗?您可以在源文件列表中使用一个变量

我只想包含一些适用于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解决方案是使用
目标源

# 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
块:

add_可执行文件(${TARGET}PUBLIC)
main.cpp
mainwindow.cpp
主窗口
mainwindow.ui
$
)

如果您愿意,这种方法也可以与命令一起使用。

使用一个变量并设置此选项是否回答您的问题?顺便说一句,我从标签中删除了
Qt
,因为我认为它对问题或解决方案并不重要。无论是否使用
Qt
framework,都是一样的。谢谢。我仍然倾向于使用2008年开始使用CMake时学到的许多技术。下一次使用这种技术时,我必须记住这一点。在我的情况下,我有时确实希望有条件地包含源文件和工厂。@drescherjm-直到几年前,我还在同一条船上。这的确是一种思想转变,但我发现它比我曾经愿意喝kool-aid的传统风格要干净得多:)
add_executable(${TARGET} PUBLIC
   main.cpp
   mainwindow.cpp
   mainwindow.h
   mainwindow.ui
   $<$<PLATFORM_ID:Windows>:
       test.c
       test.h
  >
)