在CMake中有add_executable(main main.c) ,給可執行程序鏈庫時,要使用 target_link_libraries(...) 給main鏈庫,但該command不能使用相對路徑,若最頂層的project與subproject在同一個文件夾中,需要使用link_directories(...)來顯式指明要鏈接的庫所在的路徑,可以使用相對路徑。若想不用該command,可以采取在project與subproject上一級寫CMakeLists.txt,並使用add_subdirectory方法,詳細的例子如下所示:
(1)文件的目錄結構:其中 sub_haha sub_hello top 均為 s1 文件夾下的子文件夾。
1 s1 2 ----sub_haha 3 ----sub_hello 4 ----top
其中top文件夾下的文件如下:

sub_haha文件夾下的文件如下:

sub_hello文件夾下的文件如下:

s1文件夾下的內容如下:

s1文件夾下CMakeLists.txt的內容如下:
1 cmake_minimum_required(VERSION 2.8) 2 add_subdirectory(sub_haha sub_haha) 3 add_subdirectory(sub_hello sub_hello) 4 add_subdirectory(top top)
top文件夾下CMakeLists.txt的內容如下:
1 cmake_minimum_required(VERSION 2.8) 2 include_directories(../sub_haha ../sub_hello) 3 add_executable(main main.c) 4 target_link_libraries(main haha_lib hello_lib)
sub_haha文件夾下CMakeLists.txt的內容如下:
1 cmake_minimum_required(VERSION 2.8) 2 message("message from sub_haha") 3 add_library(haha_lib SHARED haha.c)
sub_hello文件夾下CMakeLists.txt的內容如下:
1 cmake_minimum_required(VERSION 2.8) 2 message("message from sub_hello") 3 add_library(hello_lib SHARED hello.c)
注意要在頂層s1文件夾下cmake:
1 [root@VM_33_35_centos s1]# cmake . 2 -- The C compiler identification is GNU 4.4.7 3 -- The CXX compiler identification is GNU 4.4.7 4 -- Check for working C compiler: /usr/bin/cc 5 -- Check for working C compiler: /usr/bin/cc -- works 6 -- Detecting C compiler ABI info 7 -- Detecting C compiler ABI info - done 8 -- Check for working CXX compiler: /usr/bin/c++ 9 -- Check for working CXX compiler: /usr/bin/c++ -- works 10 -- Detecting CXX compiler ABI info 11 -- Detecting CXX compiler ABI info - done 12 message from sub_haha 13 message from sub_hello 14 -- Configuring done 15 -- Generating done 16 -- Build files have been written to: /root/cmake_test/same_level_lib/show/s1
make:
1 [root@VM_33_35_centos s1]# make 2 Scanning dependencies of target haha_lib 3 [ 33%] Building C object sub_haha/CMakeFiles/haha_lib.dir/haha.c.o 4 Linking C shared library libhaha_lib.so 5 [ 33%] Built target haha_lib 6 Scanning dependencies of target hello_lib 7 [ 66%] Building C object sub_hello/CMakeFiles/hello_lib.dir/hello.c.o 8 Linking C shared library libhello_lib.so 9 [ 66%] Built target hello_lib 10 Scanning dependencies of target main 11 [100%] Building C object top/CMakeFiles/main.dir/main.c.o 12 Linking C executable main 13 [100%] Built target main
此時各個文件夾內容如下所示:



可以看到兩個庫文件已經生成,可執行程序main也已經生成,使用ldd命令查看庫的鏈接狀況(注意ldd只能查看動態庫,即后綴為.so的庫文件):

可以看到已經成功鏈接到兩個動態庫。
執行main:

可以看到輸出成功。
