使用find_package CMake add_subdirectory?

时间:2015-11-13 16:33:02

标签: c cmake

我有以下项目/来源结构:

MyProject
|-MyProject
| |-src
| | |-project.c
| |
| |-CMakeLists.txt
|
|-MyLibrary
  |-include
  | |-hello.h
  |
  |-src
  | |-hello.c
  |
  |-CMakeLists.txt

MyProject/src/project.c包含MyLibrary/include/hello.h,其中包含来自系统的libusb.h(使用CMake找到)。

我正在使用以下代码在MyLibrary/CMakeLists.txt中添加libusb依赖项:

# Find libusb
find_package(LibUsb REQUIRED)

# Include libusb
include_directories(${LIBUSB_INCLUDE_DIR})

# Add dependencies
target_link_libraries(owi535 ${LIBUSB_LIBRARY})

但是,在使用MyProjectMyLibrary编译add_subdirectory时(包括target_link_libraries),我收到错误消息,指出无法找到libusb.h

我可以自己编译MyLibrary,但是编译MyProject需要libusb.h在其包含路径中,而不是。{/ p>

有没有办法让它通过添加MyLibrary作为依赖项,MyProject通过它提取libusb.h?这意味着我不需要为包含find_package的每个项目重复MyLibrary代码。

我遇到的另一个问题是类似的;我在编译Undefined symbols时在MyLibrary中调用libusb函数时收到MyProject时收到错误,但是当它自己编译MyLibrary时,没有错误。

Undefined symbols for architecture x86_64:
  "_libusb_close", referenced from:
      _my_close_method in libMyLibrary.a(hello.c.o)
  "_libusb_exit", referenced from:
      _my_exit_method in libMyLibrary.a(hello.c.o)
  "_libusb_init", referenced from:
      _my_init_method in libMyLibrary.a(hello.c.o)
  "_libusb_open_device_with_vid_pid", referenced from:
      _my_open_method in libMyLibrary.a(hello.c.o)
ld: symbol(s) not found for architecture x86_64

1 个答案:

答案 0 :(得分:1)

来自cmake documentation

  

PUBLICINTERFACE项将填充< target>的INTERFACE_INCLUDE_DIRECTORIES属性。

     

目标可以填充此属性[INTERFACE_INCLUDE_DIRECTORIES]以发布编译目标标头所需的包含目录。使用目标可以将条目添加到自己的INCLUDE_DIRECTORIES属性,例如$<TARGET_PROPERTY:foo,INTERFACE_INCLUDE_DIRECTORIES>,以使用foo接口中指定的包含目录。

因此,您需要在MyLibrary/CMakeLists.txt

中使用此功能
target_include_directories(MyLibrary PUBLIC ${LIBUSB_INCLUDE_DIR})