c - 如何在 CLion 中添加链接器标志

标签 c makefile cmake clion libsodium

<分区>

我尝试使用 libsodium,我安装了库并尝试进行最简单的测试,当使用 Makefile 制作项目时没有问题,但是当使用 CLion 和 Cmake 时,我得到“对 `sodium_init' 的 undefined reference ”

我正在使用 Ubuntu 18.04。 我发现错误的原因是需要链接以将 -lsodium 标志添加到链接(添加标志使正常的 Makefile 工作) 当我在网上搜索使用 CMake 或 CLion 链接到外部库的方法时,我发现许多解决方案都不起作用,包括:

  • add_link_options(-lsodium)
  • 设置(CMAKE_STATIC_LINKER_FLAGS“-lsodium”)

这是我正在尝试编译的代码:

#include <stdio.h>
#include <sodium.h>

int main() 
{
    if (sodium_init() < 0)
    {
        printf("sodium init error");
    }
    __uint32_t rand = randombytes_random();
    printf("hello %d, this is a random number \n", &rand);
    return 0;
}

CLion 中的完整错误消息如下所示:

MakeFiles/TestC.dir/main.c.o: In function `main':
/home/--username--/Projects/TestC/main.c:7: undefined reference to `sodium_init'
collect2: error: ld returned 1 exit status
CMakeFiles/TestC.dir/build.make:83: recipe for target 'TestC' failed
make[3]: *** [TestC] Error 1
CMakeFiles/Makefile2:72: recipe for target 'CMakeFiles/TestC.dir/all' failed
make[2]: *** [CMakeFiles/TestC.dir/all] Error 2
CMakeFiles/Makefile2:84: recipe for target 'CMakeFiles/TestC.dir/rule' failed
make[1]: *** [CMakeFiles/TestC.dir/rule] Error 2
Makefile:118: recipe for target 'TestC' failed
make: *** [TestC] Error 2

编辑: 在查看 - https://stackoverflow.com/a/43136754/7276240 后,我解决了问题 我将以下行添加到我的 CMakeLists.txt 中: target_link_libraries(TestC libsodium.a) TestC 是可执行文件的名称。

最佳答案

您可以使用常用的 find_package()find_library() CMake 命令并将其与 target_link_libraries() 链接。如果你不想手动指定路径,已经有一个 Findsodium.cmake在官方存储库中。 Here是在 Github 上找到的 CMakeLists.txt 的一个随机示例。

关于c - 如何在 CLion 中添加链接器标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56447526/

相关文章:

c - 如何从 C 源代码创建可执行的 coff 文件

c - 使用 Intel MKL 的 3D 卷积

c - Raspberry Pi GCC Makefile 和程序结构

cmake - 为dlib创建共享库

c++ - CMake在Brew上找不到OpenSSL

linux - glfw makefile 在 Ubuntu 上出现 "generating html documentation"时失败

c - 如何在Windows中使用 "make"?明格威32

c - Windows 和 Lighttpd 上的 FastCGI

c - 在 makefile 中实现子目录

c++ - 生成文件:6:目标 'all' 的配方在 ubuntu-16.04 上失败