【问题标题】:Link Google benchmark with cmake将 Google 基准与 cmake 关联
【发布时间】:2020-12-13 22:15:43
【问题描述】:

我尝试编译我的项目,包括google benchmark。这是项目结构:

$proj:
|_ benchmark
|_ include
|_ src
|_ CMakeLists.txt

在文件夹include 中,我将google benchmark 添加为链接到最新版本@73d4d5esubmodule。相反,在benchmark 文件夹中,我放置了这两个文件:

benchmark/first.cpp(存储库使用示例)

#include <benchmark/benchmark.h>

static void BM_StringCreation(benchmark::State& state) {
  for (auto _ : state)
    std::string empty_string;
}
// Register the function as a benchmark
BENCHMARK(BM_StringCreation);

// Define another benchmark
static void BM_StringCopy(benchmark::State& state) {
  std::string x = "hello";
  for (auto _ : state)
    std::string copy(x);
}
BENCHMARK(BM_StringCopy);

BENCHMARK_MAIN();

CMakeLists.txt

file(GLOB_RECURSE ALL_BENCH_CPP *.cpp)

foreach(ONE_BENCH_CPP ${ALL_BENCH_CPP})

  get_filename_component(ONE_BENCH_EXEC ${ONE_BENCH_CPP} NAME_WE)
  set(TARGET_NAME Benchmark_${ONE_BENCH_EXEC})

  add_executable(${TARGET_NAME} ${ONE_BENCH_CPP})
  set_target_properties(${TARGET_NAME} PROPERTIES OUTPUT_NAME ${ONE_BENCH_EXEC}) 
  target_include_directories(${TARGET_NAME} PUBLIC ../include/benchmark/include ${CMAKE_SOURCE_DIR}/src)
  target_link_libraries(
    ${TARGET_NAME}
    PUBLIC
    ${CMAKE_THREAD_LIBS_INIT}
  )

endforeach()

在项目根目录的CMakeLists.txt文件中,我添加了编译标志:

[...]
SET(CMAKE_CXX_FLAGS  "-pedantic -Wall -Wextra -lbenchmark -lpthread -fopenmp")
[...]

但是找不到标志-lbenchmark。编译返回此错误:

ld: 找不到 -lbenchmark 的库

如果我省略了标志,在编译过程中我会有这个输出:

架构 x86_64 的未定义符号: [build]“__ZN9benchmark10InitializeEPiPPc”,引用自: [构建] first.cpp.o 中的 _main [build] "__ZN9benchmark22RunSpecifiedBenchmarksEv",引用自: [构建] first.cpp.o 中的 _main [build] "__ZN9benchmark27ReportUnrecognizedArgumentsEiPPc",引用自: [构建] first.cpp.o 中的 _main [build] "__ZN9benchmark5State16StartKeepRunningEv",引用自: [构建] first.cpp.o 中的 __ZL17BM_StringCreationRN9benchmark5StateE [构建] first.cpp.o 中的 __ZL13BM_StringCopyRN9benchmark5StateE [...]

【问题讨论】:

    标签: c++ cmake microbenchmark google-benchmark


    【解决方案1】:

    https://github.com/google/benchmark#usage-with-cmake

    您需要另一个target_link_libraries 指向基准库,而不是尝试使用-l 设置它。 CMake 将为您处理命令行。

    【讨论】:

    • 如果我在另一个targer_link_library 之后添加target_link_libraries(${TARGET_NAME} benchmark::benchmark) 我有这个错误:CMake Error at benchmark/CMakeLists.txt:8 (add_executable):Target "Benchmark_small_dyna_dbg" links to target "benchmark::benchmark" but the target was not found. Perhaps a find_package() call is missing for an IMPORTED target, or an ALIAS target is missing?。而find_packege 不是解决问题的方法。
    • 这似乎是一个比特定于基准测试更普遍的 cmake 配置问题。您添加的find_package 没有找到包(我希望您的 cmake 日志中出现错误),或者当目标只是 benchmark 而不是 benchmark::benchmark 时,您的基准测试版本可能较旧?
    • 我在我的项目中添加了最新版本的 benchmar(带有 git 子模块)。我还将 gtest 库也添加为 git 子模块。这可能是问题所在?可以为我的项目结构举一个 cmake 的例子吗?
    猜你喜欢
    • 1970-01-01
    • 2011-09-21
    • 2012-11-27
    • 1970-01-01
    • 2012-06-25
    • 2018-03-26
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多