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?
Asked
Active
Viewed 1,036 times
2
-
`extern
A;` and the dynamic linker will resolve the symbol at link- or run-time. – Hristo Iliev Jun 19 '12 at 17:14 -
Are you sure if this would work if the shared object library is compiled separately? – MetallicPriest Jun 19 '12 at 17:14
-
Of course it would. See my answer. – Jun 19 '12 at 17:16
-
@HristoIliev Oh gosh, you were quicker. – Jun 19 '12 at 17:16
-
You could also link the executable with `-rdynamic` and then load the shared library at run-time with `dlopen("sharedlibrary.so", RTLD_GLOBAL | RTLD_NOW);` and it will still work. – Hristo Iliev Jun 19 '12 at 17:19
-
Hristo: Yes the -rdynamic flag did the trick! – MetallicPriest Jun 19 '12 at 17:32
-
See also: http://stackoverflow.com/questions/6292473/how-to-call-function-in-executable-from-my-library – ninjalj Jun 19 '12 at 19:19
2 Answers
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
-
1Note 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