简体   繁体   中英

How to make a variable declared in constructor visible in the main file

I have two c files :

  1. myconstructor.c in which there is an implementation of __attribute__ ((constructor)) so that it can execute before main : in this file I have declared a variable a .

  2. main.c in which I try to access variable a : but I get 'a' undeclared (first use in this function)

I have created a shared library in which I have included my constructor using 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;
}

You can't access local nonstatic variables of a function from another function. Especially not directly and especially if the function whose variables you want to access is finished.

Use a global. (Note that if you want to override a global defined in the main executable, you'll need to compile with -rdynamic ).

Executable example:

#!/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 ===

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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