Linux:导出要在我的共享库中使用的可执行文件的全局变量(C 语言)

问题描述 投票:0回答:3

我想访问共享库中可执行文件的全局变量?我尝试使用选项 -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;
}

由于我的代码很大,所以我只给出了我在程序中使用的示例。

c linux shared-libraries
3个回答
3
投票

应该可以。顺便说一句,你的

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

将第一个文件链接到库

常见的做法是为您的库提供一个头文件

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.c
tstlib.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
    

    请注意,您可以将共享对象与其他库链接。如果您的

    -lgdbm
    是例如,您可以将
    tstlib.c
    附加到该命令调用
    gdbm_open
    因此包括
    <gdbm.h>
    。这是共享库为您提供静态库所没有的众多功能之一。

  3. 使用

    -rdynamic

    链接可执行文件
    gcc -rdynamic tst.o -L. -ltst -o tst
    

请花时间阅读程序库操作指南


0
投票

int myVariable = 123;
语法应该已经可以工作了,因为与MSVC不同,你永远不需要
__declspec(dllexport)
关键字。

但是如果您更改了编译器的默认设置,请尝试手动设置

visibility
,请参阅示例。

示例

在应用程序(不是库)的标头中:

// Backward compatible header recurse guard.
#ifndef MY_APP_H
#define MY_APP_H

// MARK: Helpers.
#define MY_APP_EXPORT __attribute__((visibility("default")))

// MARK: Variables.
MY_APP_EXPORT extern int myVariable;
MY_APP_EXPORT extern int myOtherVariable;

#endif // MY_APP_H

在应用程序(不是库)的来源中:

#include "my-app.h"

int myVariable = 123;
int myOtherVariable = 786;

int main() {

    // ...

    return 0; // Success.
}

-1
投票

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

setFunction
:编辑此变量

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

getFunction
:返回变量

int getFunction ()
{
    return tstVar
}
© www.soinside.com 2019 - 2024. All rights reserved.