非root用户安装使用Glog和Gflags

在工程上,我们并不希望将某个版本的glog,gflags或者googletest库安装在/usr/底下,因此会有将这些库安装在项目文件夹内并且使用CMake调用的需求,本文通过实验,试图解决这个问题。

环境:Ubuntu 18.04 + CMake 3.26.0-rc4

  1. 下载googletest并安装
mkdir build && cd build
cmake ..
make -j8
  1. 下载gflags并安装
mkdir build && cd build
cmake -DBUILD_SHARED_LIBS=ON -DBUILD_STATIC_LIBS=ON -DINSTALL_HEADERS=ON -DINSTALL_SHARED_LIBS=ON -DINSTALL_STATIC_LIBS=ON ..
make -j8

注意,没有root权限,无法sudo make install

  1. 下载glog并安装
    进入CMakeLists.txt
    修改对应行如下
    option (WITH_GFLAGS "Use gflags" OFF)
mkdir build && cd build
cmake ..
make -j8

注意,没有root权限,也无法sudo make install

  1. 使用cmake实现编译链接,代码如下

test_glog.cpp

#include 
#include 

int main(int argc, char **argv) {
    google::InitGoogleLogging(argv[0]); // Init GLog
    LOG(ERROR) << "There is error !!!";

    testing::InitGoogleTest(&argc, argv); // Init GTest
    return RUN_ALL_TESTS();
}

CMakeLists.txt (假设glog,gflags,googletest都放在third_party文件夹下)

cmake_minimum_required(VERSION 3.23)
project(test_glog)
set(USE_GLOG_CATKIN FALSE)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

set(GFLAG_ROOT ${CMAKE_SOURCE_DIR}/third_party/gflags)
set(GLOG_ROOT ${CMAKE_SOURCE_DIR}/third_party/glog)
set(GTEST_ROOT ${CMAKE_SOURCE_DIR}/third_party/googletest)

include_directories(${GFLAG_ROOT}/build/include
                    ${GLOG_ROOT}/build
                    ${GTEST_ROOT}/googletest/include)

set(gflags_DIR ${CMAKE_SOURCE_DIR}/third_party/gflags/build)
find_package(gflags REQUIRED PATHS ${CMAKE_SOURCE_DIR}/third_party/gflags NO_DEFAULT_PATH)
set(glog_DIR ${CMAKE_SOURCE_DIR}/third_party/glog/build)
find_package(glog REQUIRED PATHS ${CMAKE_SOURCE_DIR}/third_party/glog NO_DEFAULT_PATH)
find_package(Threads REQUIRED)

find_library(GTEST gtest ${CMAKE_SOURCE_DIR}/third_party/googletest/build/lib)
find_library(GTEST_MAIN gtest_main ${CMAKE_SOURCE_DIR}/third_party/googletest/build/lib)

add_executable(test_glog test_glog.cpp)
target_link_libraries(test_glog ${GTEST} ${GTEST_MAIN})
target_link_libraries(test_glog ${CMAKE_THREAD_LIBS_INIT})
target_link_libraries(test_glog glog::glog)

运行结果如下

$ ./test_glog
E20230404 15:01:27.221040 30776 test_glog.cpp:6] There is error !!!
[==========] Running 0 tests from 0 test suites.
[==========] 0 tests from 0 test suites ran. (0 ms total)
[  PASSED  ] 0 tests.

你可能感兴趣的:(linux,c++)