在cmake项目中使用静态库

时间:2016-04-19 05:20:28

标签: c++ cmake static-libraries

我有两个C ++项目A和B.项目B依赖于项目A. 项目A将此结构拆分为一些子目录:

Project A
|-\inc
|  |-a1.h
|  |-a2.h
|-\src
   |-CMakeLists.txt
   |-\subdir_A1
   |  |-CMakeLists.txt
   |  |-a1.cpp
   |
   |-\subdir_A2
      |-CMakeLists.txt
      |-a2.cpp

Project B
|-\lib
   |-a1.h
   |-a2.h
   |-lib_ProjectA.a
|-\src
   |-CMakeLists.txt
   |-b.cpp

问题是项目B无法解决项目的A定义。虽然我已将target_link_libraries添加到项目B中的CMakeLists.txt,但我遇到如下错误:

  

未定义对`project_a :: a1 :: func1()"

的引用

UPD1

我设法通过从子目录(liba1.a,liba2.a)中获取所有库并将它们链接到项目来编译项目B.我想知道是否有可能调整项目A,所以我只能使用一个文件lib_ProjectA.a

UPD2

代码:

项目A

add_library (adapter
   adapter.cpp
 )

target_link_libraries (adapter PUBLIC
   net  # From project's A subdirectory 
   utils # From project's A subdirectory 
)

项目B

add_library (anthill
   functional_block.cpp)

target_link_libraries(anthill 
  ${PROJECT_SOURCE_DIR}/lib/libjsoncpp.a
  ${PROJECT_SOURCE_DIR}/lib/libadapter.a 
  ${PROJECT_SOURCE_DIR}/lib/libnet.a     # Can't compile without it   
  ${PROJECT_SOURCE_DIR}/lib/libutils.a   # Can't compile without it
)

1 个答案:

答案 0 :(得分:0)

使用OBJECT选项的最佳解决方案:

 add_library(myObjects OBJECT a.c b.c)