mardi 4 août 2015

Creating compiler independent shared objects (C++ with C interface)

On Windows DLLs with C interfaces can be used to call C++ code compiled with one compiler (e.g., GCC) from an executable compiled with another one (e.g., MSVC). However, trying to do the same on Linux using SOs has proven to be less easy.

For example, I have the following code:

#include <vector>
#include <string>

extern "C" void __attribute__ ((visibility ("default"))) foo()
{
    [&] () noexcept { std::vector<std::string> bar; bar.emplace_back("foo"); }();
}

And create a shared object as follows:

g++ -std=c++14 -shared -fvisibility=hidden -fPIC -o libso_test.so so_test.cpp

Where g++ is G++ 5.2.0.

And another file for the main executable:

extern "C" void foo();

int main(int, char**)
{
    foo();
    return 0;
}

When trying to compile it with the following command:

g++-4.8 -L. -o so_test_main so_test_main.cpp -lso_test

Where g++-4.8 is G++ 4.8.1 I get a number of errors (using g++ instead of g++-4.8 works fine but defeats the purpose):

./libso_test.so: undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)@GLIBCXX_3.4.21'
./libso_test.so: undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&&)@GLIBCXX_3.4.21'
./libso_test.so: undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()@GLIBCXX_3.4.21'
collect2: error: ld returned 1 exit status

According to the output of nm -g -D --defined-only libso_test.so, aside from the expected symbols _init _fini and foo (marked T) a large number of other symbols are exported marked W.

How can I hide these symbols properly?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire