Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Can';t编译并与动态库链接_C_Shared Libraries - Fatal编程技术网

Can';t编译并与动态库链接

Can';t编译并与动态库链接,c,shared-libraries,C,Shared Libraries,我试图通过在共享库中定义函数来编译一个简单的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) 我试过使用

我试图通过在共享库中定义函数来编译一个简单的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
hello.c

#include "greeting.h"

int main ()
{
    greeting("Daniel");
    return 0;
}
#include <stdio.h>
#include "greeting.h"

void greeting(const char* text)
{
    printf("%s\n", text);
}
问候语.h

#ifndef GREETING_H
#define GREETING_H

void greeting(const char* text);

#endif
问候语.c

#include "greeting.h"

int main ()
{
    greeting("Daniel");
    return 0;
}
#include <stdio.h>
#include "greeting.h"

void greeting(const char* text)
{
    printf("%s\n", text);
}
#包括
#包括“greeting.h”
无效问候语(常量字符*文本)
{
printf(“%s\n”,文本);
}
greeting.so正在使用
clanggreeting.c-o greeting.so-shared-fPIC

我正试图用
clang hello.c-o hello-Igreeting编译hello


有人能帮我找出我做错了什么吗?

clanghello.c-o hello-Igreeting

尝试编译并链接,但未提供要链接的库的名称:

clang hello.c -o hello -Igreeting greeting.so #<= greeting.so added
这个想法是,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\u LIBRARY\u PATH=。
部分


动态库还有很多内容,我建议您对它们进行更多的研究,例如,从Ulrich Drepper的writeup中学习。

成功了!非常感谢。有没有一种方法可以在不设置LD_LIBRARY_PATH的情况下运行它?或者告诉可执行文件在同一目录中搜索对象?@DanielP。是的,是的。我已经扩展了答案。