在共享库中分配给extern [英] assign to extern in shared library

查看:99
本文介绍了在共享库中分配给extern的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个用户定义的shell,用户可以在其中动态地将新插件加载到shell中。



在我的一些共享库中,我引用了全局变量关键字extern,例如下面的插件



I am building a user defined shell where the user can dynamically load new pluggins into the shell.

In some of my shared libraries I reference global variables using the keyword extern, such as the pluggin below

extern char *prompt;

int setprompt(char *argv[]) {
	prompt = argv[1];
	return 0;
}





,当我执行我的shell程序(链接这个库)时,我收到错误





only, when I execute my shell program (which links this library) I get the error

./setprompt.so: undefined symbol: prompt





为什么我不能为全局变量赋值?



这里是shell代码中的代码,其中包含提示的定义





Why can't I assign something to the global variable?

Here's the code from the shell code which includes the definition of prompt

char *builtin_functions[64] =  {
	"comment", "setprompt", "cd", "bgjobs", "fg", "loadpluggin", "culater"
};
char *prompt = "upsh";
void *pointers_to_functions[64];
char *background_jobs[64];
int ptr_to_func_index = 7;
int bg_index = 0;


int main()
{

推荐答案

所以你有一个可执行文件和一个共享库。库导出可执行文件使用的符号。



但您还希望库访问可执行文件中的符号。这称为反向依赖,您的可执行文件也必须导出符号。这可以通过使用 - export-dynamic 链接器选项来完成。另见第3.4节。创建程序库HOWTO 的共享库[ ^ ]。
So you have an executable and a shared library. The library exports symbols to be used by the executable.

But you also want the library to access a symbol from the executable. This is called 'reverse dependency' and your executable must also export the symbol. This can be done by using the --export-dynamic linker option. See also section 3.4. Creating a Shared Library of the Program Library HOWTO[^].


It与全球无关。这是链接器错误,而不是编译。您根本没有在任何地方定义提示符。链接器查找所有目标文件/库,但无法找到它的定义位置。显然,你没有在任何地方定义它。我希望你理解什么是定义和声明,单独编译模型的C和C概念的基础。



-SA
It has nothing to do with "global". This is a linker error, not compilation. You simply did not define prompt anywhere. The linker looks up for all object files/libraries and cannot find where it is defined. Apparently, you did not bother to defined it anywhere. I hope you understand what is definition and declaration, the basics of C and C conception of separate compilation model.

—SA


很可能,您的问题是您不了解C 链接的工作原理。你真的需要学习它,因为这是基础知识之一;没有它,任何非废话的C或C ++编程都是不可能的。请参阅我对解决方案1的评论。



您可以从这里开始:

https://bytes.com/topic/c/answers/168304-static-linkage-extern-c [ ^ ],

http://en.cppreference.com/w/cpp/language/storage_duration [ ^ ]。



-SA
Most likely, your problem is that you don't understand how C linkage works. You really need to learn it, because this is one of the basics; without it, any non-nonsense C or C++ programming is simply impossible. Please see my comment to Solution 1.

You can start here:
https://bytes.com/topic/c/answers/168304-static-linkage-extern-c[^],
http://en.cppreference.com/w/cpp/language/storage_duration[^].

—SA


这篇关于在共享库中分配给extern的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆