c - 无法编译和链接动态库
问题描述
我试图通过在共享库中定义函数来编译一个简单的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)
我用Clang和GCC都试过了,同样的错误发生了。
我已经搜索过,但没有找到类似的东西。
目录如下:
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
谁能帮我找出我做错了什么?
解决方案
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文章。
推荐阅读
- php - PHP Bootstrap 模态图像大小问题
- javascript - 大数据的 Javascript 性能问题
- javascript - 将变量从控制器中的渲染数组传递到树枝中的javascript
- c++ - 如何正确定义模板函数的模板类返回类型?
- module - Terraform 模块输出参考
- php - 从产品描述 Woocommerce 中删除链接
- json - 所有对象都必须在 json 中包含相同的信息吗?
- vb.net - 如果 Access 数据库中存在查询,我如何在 VB.Net 中进行测试
- python - 在 Python 中为 FastText 清理 Webscrape 文本
- freepascal - Indy 10 - 手动添加 cookie