博客
关于我
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 | feature_engine,一个实用的 Python 库!
    查看>>
    python | filelock,一个超酷的 Python 库!
    查看>>
    python | fire,一个强大的 Python 库!
    查看>>
    python | flanker,一个神奇的 Python 库!
    查看>>
    python | flower,一个强大的 Python 库!
    查看>>
    python | funcy,一个超强的 提供函数式编程工具 Python 库!
    查看>>
    python | ggplot,一个超强的 Python 库!
    查看>>
    python | grab,一个强大的 Python 库!
    查看>>
    python | gunicorn,一个非常实用的 Python 库!
    查看>>
    python | h5py,一个无敌的关于 HDF5 的 Python 库!
    查看>>
    python | huey,一个非常厉害的 任务调度 Python 库!
    查看>>
    python | hypothesis,一个有趣的 Python 库!
    查看>>
    python | Indico,一个超酷的 Python 库!
    查看>>
    python | isort,一个有趣的 自动整理导入语句 的Python 库!
    查看>>
    python | jinja,一个超酷的 Python 库!
    查看>>
    python | joblib,一个强大的 Python 库!
    查看>>
    python调用git bash_Python学习第70课-用Git Bash在命令行打开sublime
    查看>>
    python | jsonschema,一个实用的 验证 JSON 数据结构 Python 库!
    查看>>
    python课程的中期报告范文_课题研究中期总结报告范文
    查看>>
    python | lxml,一个超酷的 关于XML/HTML 文档 Python 库!
    查看>>