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

    你可能感兴趣的文章
    Python \r\n与\n的转换
    查看>>
    python __new__中单例的作用
    查看>>
    python | aiofiles,一个超酷的 Python 库!
    查看>>
    python | akshare,一个超强的 开源Python 金融数据接口库!
    查看>>
    python | alabaster,一个强大的 关于alabaster 主题 Python 库!
    查看>>
    python | algorithms,一个超赞的 集合常用算法的Python 库!
    查看>>
    python调用jpype 报错:OSError JVM is already started和JVM cannot be restarted
    查看>>
    python | authlib,一个强大的 Python 库!
    查看>>
    python | awswrangler,一个高效的 Python 库!
    查看>>
    python | bashplotlib,一个有趣的Python库!
    查看>>
    python | bentoml,一个超级厉害的 模型部署 Python 库!
    查看>>
    python调用jar包的模块_python调用jar包
    查看>>
    python | black,一个神奇的 代码格式化工具 Python 库!
    查看>>
    python | bleach,一个超强的 Python 库!
    查看>>
    python | cartopy,一个有趣的 Python 库!
    查看>>
    python | cloud-init,一个实用的 云计算 Python 库!
    查看>>
    python | code2flow,一个神奇的 Python 库!
    查看>>
    python | cudf,一个超实用的 Python 库!
    查看>>
    python | daphne,一个非常nice的 Python 库!
    查看>>
    python调用halcon
    查看>>