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

    你可能感兴趣的文章
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>
    npm设置淘宝镜像、升级等
    查看>>
    npm设置源地址,npm官方地址
    查看>>
    npm配置安装最新淘宝镜像,旧镜像会errror
    查看>>
    NPM酷库052:sax,按流解析XML
    查看>>
    npm错误 gyp错误 vs版本不对 msvs_version不兼容
    查看>>
    npm错误Error: Cannot find module ‘postcss-loader‘
    查看>>
    npm,yarn,cnpm 的区别
    查看>>
    NPOI之Excel——合并单元格、设置样式、输入公式
    查看>>
    NPOI初级教程
    查看>>
    NPOI利用多任务模式分批写入多个Excel
    查看>>