I believe a C++ member function declared as static
has internal linkage. When I compile libbar.cpp/libbar.hpp (below) as a shared object, I find that I can call both test1
and test2
from a separate (main) program. Why is the static member function test2
available outside of its translation unit?
// bar/libbar.hpp
struct Foo
{
void test1();
static void test2();
};
// bar/libbar.cpp
#include <iostream>
void Bar::test1() { std::cout << __PRETTY_FUNCTION__; }
void Bar::test2() { std::cout << __PRETTY_FUNCTION__; }
I compile the shared object with $CXX libbar.cpp -shared -fpic -o libbar.so
and the main
program (below) using $CXX -I bar -L bar main.cpp -Wl,-rpath,$PWD/bar -lbar
. I am using GCC and Clang on Debian.
// main.cpp
#include "libbar.hpp"
int main(int argc, char *argv[])
{
Bar b{};
b.test1();
b.test2();
return 0;
}