簡體   English   中英

如何使用cmake鏈接庫

[英]How to link library using cmake

我需要在程序中使用外部庫。 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命令來編譯示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM