Let CMake link against a specific version of libstdc++

I need to not only statically link, but also against specific version of libstdc++.a.

Details:
I’m working on a fresh installed Debian-12 at where only the version 11/12 of gcc/g++ can be installed against the official apt repository.

But my producing target app must be compiled with g+±9, so I have built gcc-9.5.0 from source and installed it.

I can use gcc-9/g+±9 to make my app, but I found that it still is linked against the STL that come with g+±12.

Although I can re-make a symbolic link that points to the new compiled libstdc++.so in order to let my app to really use the expected STL, but I’m afraid that would mess my working system(All other apps of the whole KDE desktop are using libstdc++).

So I decided to link statically my app against the STL of the version my own compiled.

This answer has pointed out the way “how to statically link against STL”, but it didn’t talk about “how to link against a specific version of STL in CMake”.

For example, my own compiled STL has been installed on /usr/local/lib64/libstdc++.a, while my working system native STL is siting on /lib64/libstdc++.a, How to let CMake to use the STL as my expecting?

Thanks!

Is -L/usr/lib64 being passed on the command line for the linker when using your custom toolchain? If so, that could be a cause. Adding it to the list of “system library directories” (I forget the variable name) may help CMake better understand the system involved.

Other than that, it is usually best to compile on the oldest distro you support and then deploy to newer versions because of issues like this.