如何修改CMake生成的链接命令中的-Ldir1为-Ldir2?
Hey there, let’s work through this library path issue you’re facing—where your CMake-generated Makefile is using -Ldir1 instead of -Ldir2 during linking, even with devtoolset-3 installed. Here’s a step-by-step breakdown of how to resolve this:
1. Track Down Where dir1 Is Coming From
First, we need to pinpoint why CMake is picking up dir1 in the first place. Devtoolset-3 sets environment variables that can influence CMake’s library search logic, so let’s check those:
- Activate devtoolset-3 with
scl enable devtoolset-3 bash - Run these commands to see if
dir1appears in library-related environment variables:echo $LIBRARY_PATH echo $LD_LIBRARY_PATH echo $CMAKE_LIBRARY_PATH
If dir1 shows up in any of these, that’s almost certainly the source of your problem.
2. Explicitly Set the Correct Path in CMakeLists.txt (Most Reliable)
The most foolproof way to ensure CMake uses dir2 is to specify it directly in your CMakeLists.txt. This avoids relying on environment variables entirely:
- Use
find_libraryto locate your library indir2(preferred overlink_directoriesfor better portability):# Replace "mylib" with your actual library name find_library(TARGET_LIB NAMES mylib PATHS /path/to/dir2 NO_DEFAULT_PATH) # Link the library to your target executable target_link_libraries(your_executable_name ${TARGET_LIB}) - Alternatively, if you need to add
dir2as a general search path for multiple libraries:link_directories(/path/to/dir2)
3. Override Paths via Environment Variables (For .bashrc Auto-Enable)
If you want this to work automatically like devtoolset-3 does, set the CMAKE_LIBRARY_PATH environment variable in your .bashrc—CMake prioritizes this variable when searching for libraries:
- Add this line to
~/.bashrc:export CMAKE_LIBRARY_PATH=/path/to/dir2:$CMAKE_LIBRARY_PATH - Reload your
.bashrcwithsource ~/.bashrc, then clear CMake’s cache and regenerate the Makefile:rm -f CMakeCache.txt rm -rf CMakeFiles ccmake .. make
4. Adjust Devtoolset-3’s Environment Variables
If devtoolset-3’s activation script is adding dir1 to your library paths, you can override this in .bashrc immediately after loading devtoolset’s config:
- Add these lines to
~/.bashrc:# Activate devtoolset-3 source /opt/rh/devtoolset-3/enable # Prepend dir2 to library paths to prioritize it over dir1 export LIBRARY_PATH=/path/to/dir2:$LIBRARY_PATH export LD_LIBRARY_PATH=/path/to/dir2:$LD_LIBRARY_PATH
This ensures every time you open a terminal, dir2 is the first path searched for libraries.
5. Clear CMake’s Cache
Don’t forget that CMake caches previous path settings, so even after making changes, you need to clear the cache to force it to pick up the new paths:
rm -f CMakeCache.txt rm -rf CMakeFiles
Then re-run ccmake or cmake to generate a fresh Makefile.
内容的提问来源于stack exchange,提问作者sancho.s ReinstateMonicaCellio

