首页 > 解决方案 > 无法编译和链接动态库

问题描述

我试图通过在共享库中定义函数来编译一个简单的hello world,但是在编译主程序时我得到:

/tmp/hello-ca67ea.o: In the function 'main':
hello.c:(.text+0x1a): reference to 'greeting(char const*)' not defined
clang: error: linker command failed with exit code 1 (use -v to see invocation)

我用ClangGCC都试过了,同样的错误发生了。

我已经搜索过,但没有找到类似的东西。

目录如下:

shared-test
 |
 |--greeting.c
 |--greeting.h
 |--hello.c

你好ç

#include "greeting.h"

int main ()
{
    greeting("Daniel");
    return 0;
}

问候.h

#ifndef GREETING_H
#define GREETING_H

void greeting(const char* text);

#endif

问候语.c

#include <stdio.h>
#include "greeting.h"

void greeting(const char* text)
{
    printf("%s\n", text);
}

greeting.so正在编译clang greeting.c -o greeting.so -shared -fPIC

我正在尝试编译你好clang hello.c -o hello -Igreeting

谁能帮我找出我做错了什么?

标签: cshared-libraries

解决方案


clang hello.c -o hello -Igreeting

尝试编译和链接,但您没有提供要链接的库的名称:

clang hello.c -o hello -Igreeting greeting.so #<= greeting.so added

然后你应该能够运行输出:

LD_LIBRARY_PATH=. ./hello 

这个想法是将 lib 放在您的系统库路径之一中,并且因为您还没有这样做,所以 LD_LIBRARY_PATH 环境变量是一种技巧,可以让它在没有它的情况下工作。

使用 Linux 上的 gcc/clang,您还可以对完整路径进行硬编码:

clang hello.c -o hello -Igreeting $PWD/greeting.so

或者您可以使动态链接器搜索相对于可执行文件位置的依赖项

clang hello.c -o hello -Igreeting '-Wl,-rpath=$ORIGIN' greeting.so

使用上述两种方法中的任何一种,您都不再需要该LD_LIBRARY_PATH=.部件。

动态库还有很多内容,我建议您对它们进行更多研究,例如,来自 Ulrich Drepper 的DSO Howto文章。


推荐阅读