Created
October 20, 2025 21:51
-
-
Save malfet/4f09cbb0ffe2e116e5871a7451ccaa7f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| a_cpp = """#include <iostream> | |
| namespace foo::bar { | |
| inline namespace baz { | |
| int inc(int x) { | |
| std::cout << "do inc from lib_a" << std::endl; | |
| return x + 1; | |
| } | |
| } // inline namespace baz | |
| void do_a(int x) { | |
| std::cout << "inc(" << x << ") = " << inc(x) << std::endl; | |
| } | |
| } // namespace foo::bar | |
| """ | |
| b_cpp = """#include <iostream> | |
| namespace foo::bar { | |
| inline namespace baz { | |
| int inc(int x) { | |
| std::cout << "inc from lib_b" << std::endl; | |
| return x + 2; | |
| } | |
| } // inline namespace baz | |
| void do_b(int x) { | |
| std::cout << "inc(inc(" << x << ")) = " << inc(inc(x)) << std::endl; | |
| } | |
| } // namespace foo::bar | |
| """ | |
| main_cpp = """ | |
| // Forward declarations | |
| namespace foo::bar { | |
| void do_a(int); | |
| void do_b(int); | |
| }; | |
| int main(int argc, const char *argv[]) { | |
| using namespace foo::bar; | |
| do_a(argc); | |
| do_b(argc); | |
| return 0; | |
| } | |
| """ | |
| if __name__ == "__main__": | |
| # Create files | |
| with open("a.cpp", "wt") as f: | |
| f.write(a_cpp) | |
| with open("b.cpp", "wt") as f: | |
| f.write(b_cpp) | |
| with open("main.cpp", "wt") as f: | |
| f.write(main_cpp) | |
| # Compile libs | |
| from subprocess import check_call | |
| check_call(f"c++ -shared -std=c++17 -O3 -fPIC -oliba.so a.cpp", shell=True) | |
| check_call(f"c++ -shared -std=c++17 -O3 -fPIC -olibb.so b.cpp", shell=True) | |
| print("Link main with liba and libb and run, observe that inc from liba is used") | |
| check_call(f"c++ -std=c++17 -O3 -fPIC main.cpp -la -lb -L. -Wl,-rpath=.", shell=True) | |
| check_call("./a.out", shell=True) | |
| print("Invert link order and run again, observe thank inc from libb is used") | |
| check_call(f"c++ -std=c++17 -O3 -fPIC main.cpp -lb -la -L. -Wl,-rpath=.", shell=True) | |
| check_call("./a.out", shell=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment