博客
关于我
CMakeLists之引入头文件(五)
阅读量:555 次
发布时间:2019-03-09

本文共 1095 字,大约阅读时间需要 3 分钟。

新建项目

客户要求创建一个新项目 t4,其目录结构如下:

t4/├── main.c├── hello.h└── src/    └── main.c

导入第三方头文件

hello.h 文件位于路径 /root/cpp_test/backup/cmake_test/t4/include/hello,并非标准系统头文件路径。因此,需在 src/CMakeLists.txt 中添加 INCLUDE_DIRECTORIES 指令:

INCLUDE_DIRECTORIES(/root/cpp_test/backup/cmake_test/t4/include/hello)

重新构建项目后,编译过程中出现了错误:main.c:(.text+0x12): undefined reference to 'func'。因为缺少动态链接到 libhello

为目标文件添加共享库

为了解决依赖问题,需在 src/CMakeLists.txt 中添加 TARGET_LINK_LIBRARIES 指令,指定共享库路径:

TARGET_LINK_LIBRARIES(main                               /root/cpp_test/backup/cmake_test/t4/thirdPath/libhello.so.1.2)

重新构建后,编译生成的可执行文件 bin/main 已正确链接到共享库 libhello.so.1.2

查看执行文件的链接情况

运行命令查看链接情况:

ldd bin/main

输出显示 bin/main 确实连接到共享库 libhello,具体路径为 libhello.so.1

修改为链接到静态库

TARGET_LINK_LIBRARIES 指令改为静态库:

TARGET_LINK_LIBRARIES(main                               /root/cpp_test/backup/cmake_test/t4/thirdPath/libhello.a)

重新构建后,再次运行 ldd src/main 检查链接结果:

ldd src/main

输出显示 bin/main 已成功连接到静态库 libhello.a

总结

以上步骤展示了使用 CMake 脚本配置项目时的关键操作,包括:

  • 添加头文件搜索路径
  • 组织和编译源代码
  • 动态链接共享库
  • 检查编译结果
  • 这些操作帮助确保了工程能够正确构建并运行,解决了动态链接依赖问题。通过实践掌握了 CMakeLists.txt 中常用指令的使用方法。

    转载地址:http://nfbpz.baihongyu.com/

    你可能感兴趣的文章
    PIL Image转Pytorch Tensor
    查看>>
    PIL&QOOT;IOERROR:带有大图像的图像文件被截断(&Q)
    查看>>
    PIL.Image、cv2的img、bytes相互转换
    查看>>
    PIL.Image进行图像融合显示(Image.blend)
    查看>>
    pilicat-dfs 霹雳猫-分布式文件系统
    查看>>
    Pillow lacks the JPEG 2000 plugin
    查看>>
    SpringBoot之ElasticsearchRestTemplate常用示例
    查看>>
    ping 全网段CMD命令
    查看>>
    ping 命令的七种用法,看完瞬间成大神
    查看>>
    Pinia入门(快速上手)
    查看>>
    Pinia:$patch的使用场景
    查看>>
    Pinia:$subscribe()的使用场景
    查看>>
    Pinpoint对Kubernetes关键业务模块进行全链路监控
    查看>>
    Pinterest 大规模缓存集群的架构剖析
    查看>>
    pintos project (2) Project 1 Thread -Mission 1 Code
    查看>>
    PinYin4j库的使用
    查看>>
    PIP
    查看>>
    pip install goose-extractor // SyntaxError: Missing parentheses in call to 'print'
    查看>>
    pip install mysqlclient报错
    查看>>
    pip install 出现报asciii码错误的解决
    查看>>