Raulp
Raulp

Reputation: 8196

What does exporting a symbol mean?

I have been looking for this term "exporting a symbol". What does exporting a symbol mean in C/C++ or with respect to the libraries (shared/static)? From where do we export the symbols and why? What is the relation of exporting a symbol with the name mangling by the compiler?

Upvotes: 16

Views: 10491

Answers (1)

littleadv
littleadv

Reputation: 20282

Exporting a symbol means "advertising" its existence in your object file/library and where it is, so that it could be imported (=linked to) by other modules.

Link can be done statically or dynamically, but either way the linker has to know what the symbol is, and where it is, and the exported symbol and the imported symbol must match for it to happen. Name mangling is related to that (C++ name mangling includes symbol's type definition in the symbol name, and the mangling of the exported and imported symbol must match for the linker to link the import-export correctly).


Example:

Suppose you have a library "STANDARDC" (random name) and your program SOMEPROG. Program SOMEPROG needs to print to console, so it will call printf. But you don't actually implement printf in your program SOMEPROG, you just use it (=import it), while the implementation is elsewhere.

The library STANDARDC has a list of symbols it exports which includes all the functions that are implemented in that library and can be called from outside (=exported functions). printf is one of such functions, so it will appear in the exported list.

The compiler goes through your SOMEPROG.C and sees that you reference printf, but there's no implementation for it. The compiler adds the printf to the list of the imported symbols for the resulting SOMEPROG.obj, for the linker to link the actual implementation in.

The linker takes your SOMEPROG.obj file and the STANDARDC .lib file, and sees what functions are used in the SOMEPROG.obj. The linker finds that printf is not implemented, it is imported, so the linker looks through all the .lib files it has and finds matching printf in the exported list of STANDARDC. It takes the implementation of printf from STANDARDC and links it into your program everywhere you reference the imported symbol printf.

Upvotes: 34

Related Questions