How do I use visibility attributes to hide symbols?

In C++, visibility attributes are used to control the visibility of symbols in shared libraries or dynamic link libraries (DLLs). This is particularly useful to prevent certain functions or classes from being exposed to other components, ensuring better encapsulation of the code and reducing potential name clashes.

Using Visibility Attributes

To hide symbols in a shared library, you can use the `__attribute__((visibility("hidden")))` attribute in GCC or Clang. Here’s how you can implement this:

// Example of hiding a symbol in C++ #include <iostream> // Marking the function with hidden visibility __attribute__((visibility("hidden"))) void hiddenFunction() { std::cout << "This function is hidden." << std::endl; } void visibleFunction() { std::cout << "This function is visible." << std::endl; } int main() { visibleFunction(); // Uncommenting the next line will cause a link error if hiddenFunction is not exposed // hiddenFunction(); return 0; }

C++ visibility attributes hide symbols __attribute__((visibility)) shared libraries encapsulation