DLL __attribute__

DLL attribute 详解

The #define TC_DLL attribute((visibility("default"))) macro is used in C/C++ code to control symbol visibility when compiling shared libraries (DLLs on Windows or .so files on Unix-like systems).

Explanation:

1. attribute((visibility("default"))):

This is a GCC/Clang compiler attribute that explicitly marks a symbol (function, class, variable, etc.) as "visible" outside the shared library.
Symbols with visibility("default") will be exported and can be linked against by other programs or libraries.
Conversely, visibility("hidden") hides the symbol, making it internal to the library (improves optimization and reduces symbol collisions).

2. Purpose of MLTC_DLL:

The macro TC_DLL is a shorthand for this attribute, making the code cleaner and more portable.
When you annotate a symbol with TC_DLL, it ensures the symbol is exported in the shared library.

Example Usage:

// Export this function in the shared library
TC_DLL void my_public_function() {
    // ...
}

// This function is NOT exported (hidden by default)
void my_internal_function() {
    // ...
}

Cross-Platform Compatibility:

On Windows, you might see similar functionality using __declspec(dllexport):

#ifdef _WIN32
  #define TC_DLL __declspec(dllexport)
#else
  #define TC_DLL __attribute__((visibility("default")))
#endif

This ensures the macro works across different platforms.

Why Use It?

Explicitly controlling symbol visibility helps:
Reduce library size by hiding unnecessary symbols.
Avoid symbol clashes between libraries.
Improve load times (fewer symbols to resolve).
If you're working on a shared library, this macro is likely used to mark which symbols should be exposed to users of the library.

posted @ 2025-04-23 18:04  michaelchengjl  阅读(6)  评论(0)    收藏  举报