使用g++编译含Google Test子模块程序时提示“g++ is not a full path”
Let's break down your problem and fix it step by step.
Core Cause of the Error
The error "g++ is not a full path" pops up because CMake often requires an absolute path for the compiler executable when you set CMAKE_CXX_COMPILER directly in your CMakeLists.txt. Using just g++ might fail if CMake can't reliably resolve the full executable path from your system's environment variables.
Solution 1: Use an Absolute Path for g++
First, find the full path to your g++ executable. Run this in your terminal:
which g++
You'll get an output like /usr/bin/g++ (the path varies by system). Update your CMAKE_CXX_COMPILER line to use this absolute path:
set(CMAKE_CXX_COMPILER "/usr/bin/g++")
Solution 2: Let CMake Detect the Compiler (Recommended)
You don't need to hardcode CMAKE_CXX_COMPILER in your CMakeLists.txt at all. CMake automatically detects available C++ compilers on your system. If you specifically want to use g++, specify it when running CMake instead:
cmake -DCMAKE_CXX_COMPILER=g++ ..
This avoids hardcoding paths that might differ across systems.
Fixing Other Issues in Your CMakeLists.txt
Your current CMakeLists has a few other problems that will cause errors once you fix the compiler issue:
- Incorrect
add_subdirectorypath: Since you added googletest as a submodule in yourtestgoogletestdirectory, the path should begoogletest, not../googletest. - Unfinished
target_include_directoriesline: You need to specify your own test target and complete the include directory setup. - Better include directory handling: Linking against gtest/gmock targets automatically pulls in their header directories, so you don't need to set them manually.
Here's a corrected, complete CMakeLists.txt example for your project:
cmake_minimum_required(VERSION 3.5.1) project(try_googletest) # Optional: Auto-find g++ path to avoid hardcoding find_program(GPP_EXECUTABLE g++) if(GPP_EXECUTABLE) set(CMAKE_CXX_COMPILER ${GPP_EXECUTABLE}) endif() # Add the googletest submodule with correct path add_subdirectory(googletest gtest_build) # Create your test executable (replace test_main.cpp with your actual test file) add_executable(my_tests test_main.cpp) # Link against gtest/gmock - this auto-includes their header directories target_link_libraries(my_tests gtest gmock_main) # Optional: Enforce C++ standard (adjust version as needed) target_compile_features(my_tests PRIVATE cxx_std_17)
Final Build Steps
Once your CMakeLists.txt is fixed, run these commands to build your project:
mkdir build cd build cmake .. make
内容的提问来源于stack exchange,提问作者Codoscope

