【问题标题】:Set up cmakelist correctly to compile project正确设置 cmakelist 以编译项目
【发布时间】:2016-04-13 01:35:35
【问题描述】:

这是我的工作目录:

app
|___include
  |___file1.h
  |___file2.h
  |___file3.h
  !___ ...
|___src
  |___file1.c
  |___file2.c
  |___file3.c
  |___ ...
|__CMakeLists.txt
|__mainapp.c

这是我的CMakeLists.txt

cmake_minimum_required(VERSION 3.5.1)
project(app)
include_directories(include)
file(GLOB SOURCES src/*.c)
add_executable(file3 src/file3.c)
target_link_libraries(file3 m ${SOURCES})

然后我执行以下操作:

$cmake .
$make

但我得到错误:

[ 50%] Building C object CMakeFiles/file3.dir/src/file3.c.o
[100%] Linking C executable file3
src/file3.c:1:19: fatal error: file1.h: File does not exist

file3.c 只是:

#include "file1.h"
#include "file2.h"

int foo3(int a, int b){
    return foo1(a,b) + foo2(a,b);
}

如何正确设置 CMakeLists?

【问题讨论】:

    标签: c compilation makefile cmake


    【解决方案1】:

    您正在将源文件链接到您的可执行文件,但您应该编译它们。

    target_link_libraries(file3 m ${SOURCES})
    

    通常您将所有源文件放入 add_executable 以进行编译,并且仅链接诸如 m 之类的库(用于数学函数的 libm)。

    add_executable(file3 ${SOURCES})
    target_link_libraries(file3 m)
    

    这当然只有在其他文件都不包含 main 函数的情况下才有效。

    您的 include_directories(include) 作为 -Iinclude 附加到 gcc 调用,它在编译期间使用。 https://gcc.gnu.org/onlinedocs/cpp/Include-Syntax.html。您可以使用 make VERBOSE=1 查看您的 gcc 调用。

    在链接期间 gcc 不再出现,这就是为什么它告诉您找不到该功能(之后它可能会在其他地方失败)

    您还可以使用您的源代码构建一个库,并将您的可执行文件链接到该库。但是不要在库的源代码中包含 file3。

    【讨论】:

      【解决方案2】:

      使用

      #include "file1.h"
      

      在当前目录而不是其他包含的目录中搜索 file.h。

      使用

      #include <file.h>
      

      改为。

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-02
        • 1970-01-01
        • 1970-01-01
        • 2012-12-10
        • 1970-01-01
        • 1970-01-01
        • 2015-12-27
        • 2019-12-03
        相关资源
        最近更新 更多