繁体   English   中英

如何在共享库中访问可执行文件的全局变量(c - linux)

[英]How to access the global variable of executable in shared library (c - linux)

我想在共享库中访问可执行文件的全局变量? 我试图使用选项-export-dynamic进行编译,但没有运气。

我试过用extern关键词。 这也行不通。

任何帮助或建议都是值得的。

环境c - Linux

可执行文件: - tst.c

int tstVar = 5;

void main(){
funInso();
    printf("tstVar %d", tstVar);
}

lib: - tstLib.c

extern int tstVar;

void funInso(){
   tstVar = 50;
}

由于我的代码很大,我只是提供了我在程序中使用的示例。

它应该工作。 顺便说一下,你的tst.c缺少#include <stdio.h> 而其main应返回ìnt与如结束return 0;

/* file tst.c */
#include <stdio.h>
int tstVar = 5;
extern void funInso(void);

int main(){
  funInso();
  printf("tstVar %d\n", tstVar);
  return 0;
}

/* file tstlib.c */
extern int tstVar;

void funInso(){
   tstVar = 50;
}

我用gcc -Wall -c tst.c编译了第一个文件,我用gcc -Wall -c tstlib.c编译了第二个文件。 我用它做了一个图书馆

 ar r libtst.a tstlib.o
 ranlib libtst.a

然后我用gcc -Wall tst.o -L. -ltst -o tst将第一个文件链接到库gcc -Wall tst.o -L. -ltst -o tst gcc -Wall tst.o -L. -ltst -o tst

通常的做法是在库中包含一个头文件tstlib.h ,它包含例如

 #ifndef TSTLIB_H_
 #define TSTLIB_H_
 /* a useful explanation about tstVar.  */
 extern int tstVar;

 /* the role of funInso. */
 extern void funInso(void);
 #endif /*TSTLIB_H */

并且tst.ctstlib.c都包含#include "tstlib.h"

如果共享库,您应该

  1. 在位置无关代码模式下编译库文件

     gcc -Wall -fpic -c tstlib.c -o tstlib.pic.o 
  2. -shared链接库

     gcc -shared tstlib.pic.o -o libtst.so 

    请注意,您可以将共享对象与其他库链接。 如果你的tstlib.c是例如调用gdbm_open ,那么你可以将-lgdbm附加到该命令,因此包括<gdbm.h> 这是共享库为静态库提供的众多功能之一。

  3. -rdynamic链接可执行文件

     gcc -rdynamic tst.o -L. -ltst -o tst 

请花点时间阅读Program Library Howto

你的tstVar变量可以在lib中定义。 你可以通过函数共享这个变量: setFunction :编辑这个变量

void setFunction (int v)
{
    tstVar = v;
}

getFunction :返回变量

int getFunction ()
{
    return tstVar
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM