google / benchmark

A microbenchmark support library
Apache License 2.0
8.59k stars 1.57k forks source link

[FR] Add `CMake` option to disable `benchmark_main` target #1748

Closed romintomasetti closed 5 months ago

romintomasetti commented 5 months ago

Is your feature request related to a problem? Please describe.

To my knowledge, the CMake target benchmark::benchmark_main mainly bundles benchmark_main.cc, and links it to benchmark::benchmark. Then, it can be used by the user that does not need a custom int main() and is happy with the one in benchmark_main.cc.

In our case, we need a custom int main() (MPI initialization, GPU backends, and so on). Therefore, we never use benchmark::benchmark_main.

But it is always compiled... This is a waste of resources.

Describe the solution you'd like

Add a CMake option like:

option(BENCHMARK_ENABLE_MAIN "Build benchmark::benchmark_main target." ON)

By default, it would be ON to avoid downstream project failures.

If you agree, I'll be glad to make a PR for this! Thanks.

(Tagging @maartenarnst)

LebedevRI commented 5 months ago

If you build benchmark as a cmake sub-project (see https://github.com/google/benchmark/blob/e990563876ef92990e873dc5b479d3b79cda2547/cmake/GoogleTest.cmake + https://github.com/google/benchmark/blob/e990563876ef92990e873dc5b479d3b79cda2547/CMakeLists.txt#L344), you should just do

add_subdirectory(${GOOGLETEST_SOURCE_DIR}
                 ${GOOGLETEST_BINARY_DIR}
                 EXCLUDE_FROM_ALL) # !!!

to only build what is actually transitively needed by your code.

If you build it as a normal package, does it really measurably affect the compile time? The fact that benchmark.h isn't IWYU-clean has much much worse impact on compile-time than said benchmark_main.

romintomasetti commented 5 months ago

Indeed, the EXCLUDE_FROM_ALL just worked! I didn't know about this option. Thanks a lot!