在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 [[email protected]_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 [[email protected]_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:
可以看到输出成功。
时间: 2024-10-17 06:01:29