如何使在构造函数中声明的变量在主文件中可见

时间:2019-05-16 10:32:28

标签: c

我有两个c文件:

  1. myconstructor.c,其中实现了__attribute__ ((constructor)),因此它可以在main之前执行 :在此文件中,我声明了一个变量a

  2. main.c,在其中尝试访问变量a:但是我得到了‘a’ undeclared (first use in this function)

我创建了一个共享库,其中使用LD_PRELOAD包含了我的构造函数。

__attribute__ ((constructor))
void myconstructor(){
    int a=5;
    printf("Hello from the constructor\n");

 int main(){
    printf("try to print a from  the main : %d\n",a);
    return 0;
}

1 个答案:

答案 0 :(得分:2)

您不能从另一个函数访问一个函数的局部非静态变量。特别是不能直接访问,尤其是要访问其变量的函数完成时。

使用全局。 (请注意,如果要覆盖主可执行文件中定义的全局变量,则需要使用-rdynamic进行编译。)

可执行示例:

#!/bin/sh -eu
cat > lib.c <<'EOF'
#include <stdio.h>
int a = 5;
__attribute__ ((constructor))
static void myconstructor(void)
{
    a = 53; //pointless
    //^if the init value is known, you can simply use 
    //static initialization, omitting the constructor

    printf("Hello from the constructor\n");
}
EOF

cat > main.c <<'EOF'
#include <stdio.h>
#if EXTERN
extern int a;
#else
int a = 0;
#endif

int main(void)
{
    printf("try to print a from  the main : %d\n",a);
    return 0;
}
EOF
gcc lib.c -fpic -shared -o liblib.so
gcc -rdynamic  main.c -o inbuilt_overridable #-rdynamic makes the global overridable
gcc -L$PWD -DEXTERN main.c -llib -o nonabsolute_dynamic_lib
gcc -DEXTERN main.c $PWD/liblib.so  -o absolute_dynamic_lib

set -x
echo INBUILT
./inbuilt_overridable
echo ===

echo NON-ABSOLUTE DYNAMIC LIB
#if the lib isn't in standard system locations, you need the LD_LIBRARY_PATH env variable
LD_LIBRARY_PATH=$PWD ./nonabsolute_dynamic_lib
echo ===

echo ABSOLUTE LIB
#I think Cygwin doesn't support this, but Linux definitely does
./absolute_dynamic_lib
echo ===

echo INBUILT OVERRIDDEN
LD_PRELOAD=$PWD/liblib.so ./inbuilt_overridable
echo ===