【问题标题】:CMakeLists issue with STATIC library ar errorCMakeLists 与 STATIC 库 ar 错误有关的问题
【发布时间】:2022-09-23 02:16:27
【问题描述】:

我有一个结构如下所示的项目:

+project
|- include
|    |- linkedlists
|    |- stacks
|    ...
|- lib
|    |- linkedlists
|    |- stacks
|    ...
|- src
    | ...

这些目录中的每一个都有自己的CMakeLists.txt 文件,这些文件是通过add_subdirectory() 添加的。

我在lib/linkedlists/ 中的 CMakeLists.txt 遇到问题。这是它的内容:

project(linkedlists)

# ignore the missing cmake_minimum_required() it was set in the file at the rootdir.

# added this here because I wanted to run it independently. This was correctly set in the file at the rootdir.
include_directories(../../include)

# I am nesting these vars to produce libs and executables in a specific directory structure. 
# In the case of this file, it is supposed to build libs in ${CMAKE_BINARY_DIR}/libs/
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${PROJECT_NAME})
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}/${PROJECT_NAME})

# add_library(single_ll SHARED single_ll.c)
add_library(single_ll STATIC single_ll.c)
add_library(double_ll SHARED double_ll.c)
add_library(circular_ll SHARED circular_ll.c)

如果库设置为SHARED,这可以正常工作。当设置为STATIC 或未指定时(在这种情况下,它会将其视为静态),会向我抛出错误:

$ make
Consolidate compiler generated dependencies of target single_ll
[ 16%] Linking C static library /linkedlists/libsingle_ll.a
ar: /linkedlists/libsingle_ll.a: No such file or directory
make[2]: *** [/linkedlists/libsingle_ll.a] Error 1
make[1]: *** [CMakeFiles/single_ll.dir/all] Error 2
make: *** [all] Error 2

我是 CMake 的初学者,我也不是共享库或静态库的专家,尽管我花了一些时间尝试在线阅读并自己弄清楚。如果我的理解存在根本性缺陷并且 CMake 的行为应如此,请告诉我一个我应该阅读的主题。

如果我的 CMakeLists.txt 文件可能有问题,请帮我纠正它。

    标签: c cmake


    【解决方案1】:

    似乎您正在以一种由于访问权限而不允许创建输出文件的方式设置您的项目。标准用户不太可能具有在文件系统根目录中创建目录linkedlists 的权限。

    此问题的可能原因是最初未设置 CMAKE_ARCHIVE_OUTPUT_DIRECTORY,导致分配了值 /linkedlists,因此到输出的存档路径为 /linkedlists/libsingle_ll.a。使用共享库时出现差异的原因可能是在使用add_subdirectory 之前设置了CMAKE_LIBRARY_OUTPUT_DIRECTORY 以包含显示的CMakeLists.txt 文件。

    如果您确实希望在特定目录中构建库,我建议使用相对于构建目录的根目录的目录:

    set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
    set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
    

    注意:如果这是尝试直接在您希望它们在文件系统上结束的最终位置直接构建二进制文件,我建议使用install(TARGETS),它允许您在没有管理员权限的情况下构建库,方法是将构建和复制到文件系统分为 2 个单独的步骤,如下所示:

    cmake --build .
    sudo cmake --install . --prefix /usr/local
    

    (不这样做将要求您始终使用管理员权限进行构建,这将使 root 成为构建期间创建的所有文件的所有者,这意味着任何重建都需要 root 权限才能覆盖任何这些文件......)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-17
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      相关资源
      最近更新 更多