2

Say I have a program which uses the shared object library X, which is compiled separately from my program. Now when I write the code for X, I need to refer a variable, say A, which is declared in my program (which will be using the X library). How can I refer the variable A inside the code for X? Weak references? extern? Or some other technique?

MetallicPriest
  • 29,191
  • 52
  • 200
  • 356

2 Answers2

5

Use the extern keyword:

extern int A;

// later:
call_a_function(A);
A = something_else;

Yes, it works if the shared object is compiled separately. In that case, the compiler internally generates an exported symbol with the name of the variable and the dynamic linker looks it up.

Update: as @Hristo pointed out, in addition, you have to specify the -rdynamic linker flag when building the units to make this work.

  • I tried to do that but at runtime, it says lookup error, undefined symbol. Note that I LD_PRELOADed the X library. – MetallicPriest Jun 19 '12 at 17:20
  • Maybe the shared library declared the variable as `static`? If so, there's no way you can access it. –  Jun 19 '12 at 17:24
  • It's the opposite situation he is talking about - external library accessing symbols from the executable. Probably the symbol was defined `extern` in both the executable and the library. – Hristo Iliev Jun 19 '12 at 17:28
  • No, it was defined without any attributes in the main program and extern in the library. Also I'm LD_PRELOADing the library. Perhaps that is why its not working. – MetallicPriest Jun 19 '12 at 17:31
  • 1
    Note that you only need `-rdynamic` for the executable, since on ELF executables don't export their symbols to other DSOs by default, while DSOs do export their symbols to other DSOs by default. – ninjalj Jun 19 '12 at 19:24
4

The -rdynamic flag needs to be specified when compiling the program to make this work. Then the shared object library can refer the variable in the program by simply using the extern keyword.

MetallicPriest
  • 29,191
  • 52
  • 200
  • 356