Taking Boost as an example, why am I able to link against boost::filesystem
from my C++ program, when C++ does not have a stable ABI.
I have Boost installed in my system, and a toy program is able to link using -lboost_filesystem
, even though boost::filesystem
exposes a C++ API ( no extern 'C' ).
So, is it possible to create C++ shared libraries that can be linked by various compiler versions? How does Boost achieve this without "extern C"?
I tried:
#include <iostream>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
int main() {
// Replace "/path/to/directory" with the path to the directory you want to list
std::string directory_path = "/path/to/directory";
try {
// Check if the given path exists and is a directory
if (fs::exists(directory_path) && fs::is_directory(directory_path)) {
std::cout << "Listing files in directory: " << directory_path << std::endl;
// Iterate through the files in the directory
for (const auto& entry : fs::directory_iterator(directory_path)) {
std::cout << entry.path() << std::endl;
}
} else {
std::cerr << "Error: Invalid directory path." << std::endl;
return 1;
}
} catch (const fs::filesystem_error& ex) {
std::cerr << "Error: " << ex.what() << std::endl;
return 1;
}
return 0;
}
g++ -o fs fs.cpp -I/usr/include/boost -I/usr/include/boost/filesystem -I/usr/include/boost/system -lboost_system -lboost_filesystem -std=c++14
Expectation: Should get linking errors as C++ does not have a stable ABI
Got: Compilation Succeeded.
I'm not sure about ABI per se, but the real crux of linking a C++ library built by one compiler with a program compiled with another compiler would rely on both compilers sharing the same name mangling schema.
And indeed, g++ and clang++ work the same and have had the same schema for years.
But as this question and answer reveal, trying to do something similar by compiling a library on Windows with MinGW and expecting it to link with Visual Studio, doesn't work. Probably not possible unless something has changed in recent years.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With