【问题标题】:How to link libraries using CMake [closed]如何使用 CMake 链接库 [关闭]
【发布时间】:2018-11-23 16:57:01
【问题描述】:

我目前正在尝试弄清楚如何在 CMake 中链接库。据我所知,我已经正确设置了所有内容。但是,当我尝试构建时,出现以下错误。

test/src/test.cpp:1:10: fatal error: lib.h: No such file or directory
#include "lib.h"
         ^~~~~~~
compilation terminated.
make[2]: *** [CMakeFiles/a.out.dir/build.make:63: 
CMakeFiles/a.out.dir/src/test.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:110: CMakeFiles/a.out.dir/all] Error 2
make: *** [Makefile:84: all] Error 2

我的文件结构是

CMakeLists.txt
\src
    test.cpp
    \lib
        lib.h
        lib.cpp

这是我的文件

CMakeLists.txt:

cmake_minimum_required(VERSION 2.9 FATAL_ERROR)
project("test")

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)

add_library(lib STATIC src/lib/lib.cpp)

add_executable(a.out src/test.cpp )
target_link_libraries(a.out lib)

src/test.cpp:

#include "lib.h"

int main(){
    hello();
    return 0;
}

src/lib/lib.h

#include <iostream>

void hello();

和 src/lib/lib.hpp

#include "lib.h"

void hello(){
    std::cout << "Hello World" << std::endl;
}

除非我弄错了,否则无论何时静态链接都不必

#include "path/to/file/file.h"

你可以

#include "file.h"

【问题讨论】:

  • 这不是链接问题,而是编译问题
  • 你错了,你需要使用CMake的include_directories()指令添加.h文件的目录。
  • 其实好像是#include "lib/lib.h"(本地包含,实际文件路径错误)

标签: c++ cmake static-linking


【解决方案1】:

包含您的标头的目录不在包含路径中;你可以使用

target_include_directories(a.out PUBLIC ${CMAKE_SOURCE_DIR}/src/lib)

指定要添加到二进制编译的路径

有关语法的更多详细信息,请参阅https://cmake.org/cmake/help/v3.0/command/target_include_directories.html。

【讨论】:

    【解决方案2】:

    添加到 CMakeList.txt:

    include_directories("./src/lib")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-18
      • 2019-12-22
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多