Your question may depend on the nature of the shared object format and implementation. Since you tagged your question [gnu], the most likely format for you to be targeting is probably ELF, the one used by pretty much all modern Linuxes and many other flavors of Unix.
I wonder if a function in a shared object use a global in the same object, would the variable still be available for the function when loaded with dlopen, dlsym and then dlclose?
With ELF, yes, unless the dynamic linker finds a different global with the same name earlier in its search path. Note also that dlopen()
ing a shared object makes its contents available in more ways than just via dlsym()
. The dynamic linker treats such objects pretty much the same way that it does shared libraries that are automatically loaded with the program.
It might be worth your while to read Ulrich Drepper's description of DSOs and the dynamic linking process. It's very good, and about as easy to read as you can hope for with a subject of this complexity. (Which is quite different from saying that it's an easy read.)