博客
关于我
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/

    你可能感兴趣的文章
    Private Destructor
    查看>>
    private和protected能同时修饰成员变量吗_天天用注解你了解注解是怎么实现的吗?...
    查看>>
    privoxy Invalid header received from client.
    查看>>
    Privoxy代码下载
    查看>>
    Probabilistic-Programming-and-Bayesian-Methods-for-Hackers
    查看>>
    pytorch中的求和函数sum(axis=x)解释
    查看>>
    Problem F: 质心算法
    查看>>
    Problem N HDU 2612 Find a way (两次BFS求最值)
    查看>>
    Process /usr/libexec/gdu-notification-daemon was killed by signal 6 (SIGABRT)
    查看>>
    process.env.VUE_APP_BASE_API 获取不到
    查看>>
    Process.run() 和 Process.start() 之间的区别
    查看>>
    Processes
    查看>>
    Processing通过编程实现艺术设计_实现艺术和现实的交互---数据设计分析002
    查看>>
    ProcessOnLoading
    查看>>
    SpringBoot中集成screw(螺丝钉)实现数据库表结构文档生成
    查看>>
    PROFINET 模拟器使用教程
    查看>>
    Program type already present: android.support.v4.widget.EdgeEffectCompat
    查看>>
    PyTorch中文版官方教程来啦(附下载)
    查看>>
    Progress Kemp LoadMaster 远程命令执行漏洞复现(CVE-2024-1212)
    查看>>
    Project configuration is not up-to-date with pom.xml. Run Maven->Update Project
    查看>>