我需要在程序中使用外部库。 (https://github.com/davidmoreno/onion
我是CMake(以及这种编译程序的方式)的新手。

该库包含CMakeLists.txt文件,所以我想我应该可以使用它。
但是当我尝试编译时,例如hello world程序示例(/ onion / examples / hello /)。我收到一个错误,即CMake无法链接(甚至找不到)诸如onion.h之类的使用过的库。

为了进行编译,我正在创建一个子目录“ build”,从中执行命令cmake ..然后是cmake --build .

这是hello world程序的源文件。 (https://github.com/davidmoreno/onion/tree/master/examples/hello

CMakeLists.txt:

include_directories (${PROJECT_SOURCE_DIR}/src/)

add_executable(hello hello.c)
target_link_libraries(hello onion)


hello.c(仅标头):

#include <onion/onion.h>
#include <onion/log.h>
#include <onion/version.h>
#include <signal.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>


这是构建输出:

open# cd build/

open# cmake ..
CMake Warning (dev) in CMakeLists.txt:
  No cmake_minimum_required command is present.  A line of code such as

    cmake_minimum_required(VERSION 3.10)

  should be added at the top of the file.  The version specified may be lower
  if you wish to support older CMake versions for this project.  For more
  information run "cmake --help-policy CMP0000".
This warning is for project developers.  Use -Wno-dev to suppress it.

-- Configuring done
-- Generating done
-- Build files have been written to: /home/user1/onion/examples/hello/build

open# cmake --build .
Scanning dependencies of target hello
[ 50%] Building C object CMakeFiles/hello.dir/hello.o
/home/user1/onion/examples/hello/hello.c:18:10: fatal error: 'onion/onion.h'
      file not found
#include <onion/onion.h>
         ^~~~~~~~~~~~~~~
1 error generated.
*** Error 1 in . (CMakeFiles/hello.dir/build.make:63 'CMakeFiles/hello.dir/hello.o': /usr/bin/cc  -I/home/user1/onion/examples/hello/src   -...)
*** Error 1 in . (CMakeFiles/Makefile2:68 'CMakeFiles/hello.dir/all')
*** Error 1 in /home/user1/onion/examples/hello/build (Makefile:84 'all')


我尝试了许多解决方案,但没有一个对我有用。

谢谢你的帮助。

最佳答案

基于此存储库设置,您应该通过使用存储库中的顶级CMakeLists.txt文件而不是通过对/onion/examples/hello/目录中的文件运行CMake来编译此示例。通过从顶层运行,您可以选择包括所有示例(默认情况下它们已启用)。

通过从/onion/examples/hello/目录运行CMake,include_directories()命令将相对于当前目录进行解析。您的编译流中的“ include”行可以证明这一点:

-I/home/user1/onion/examples/hello/src


hello示例指向<onion/onion.h>,但是头文件在您包含的目录中不存在。而是它们在这里:

/home/user1/onion/src/onion/onion.h


因此,解决此问题的最简单方法是通过从存储库的根目录运行cmake命令来编译示例。

08-19 12:48