Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cmake and gcc combine

Tags:

gcc

cmake

I have many source files in source directory. For example a.c, b.c, c.c and want to compile it by gcc with -combine option.

set(CMAKE_C_FLAGS "-combine")
set(SRC a.c b.c c.c)
add_executable(a.out ${SRC})

Cmake compiles each *.c file in object file, but I want to compile all sources to one object. How can I get this.

In terms of gcc:

gcc -combine a.c b.c c.c -o module.o
ar rcs library.a module.o

But cmake uses per-module translation of sources.

gcc a.c -o a.o
gcc b.c -o b.o
gcc c.c -o c.o
ar rcs library.a a.o b.o c.o

Translation with combine could speed up performance of program. I couldn't use LTO which could resolve the same problem in cmake due to old version of gcc.

Thanks.

like image 761
Igor Petushkov Avatar asked Jun 14 '11 16:06

Igor Petushkov


People also ask

Is Cmake using GCC?

cmake and make stuffs are basically just tools in using g++ / gcc.

What compiler does Cmake use?

It has minimal dependencies, requiring only a C++ compiler on its own build system. CMake is distributed as open-source software under a permissive BSD-3-Clause license.

How do I merge object files?

select the "Object" folder and click the objects you would like to append/link to your project. Several objects can be selected by SHIFT+RIGHT click on them. Appending is merging the object into your current blend file and active scene/layer. By linking, the object is not copied but linked to the original .


1 Answers

Use add_custom_target/add_custom_command.

In any way it is non-portable construction, so here simple example

[project root] with two folders in it [src] - here N files, [build] for binary, and CMakeLists.txt

cmake_minimum_required(VERSION 2.6.0 FATAL_ERROR)
set(TARGET_NAME whole)
project(${TARGET_NAME} C)

file(GLOB SRC_FILES src/*.c)

add_custom_target(${TARGET_NAME} ${CMAKE_C_COMPILER} -flto -fwhole-program ${SRC_FILES} -o ${TARGET_NAME})

In build folder run cmake ..; make VERBOSE=1 whole

This will make the work for you.

But, -fwhole-program work only with executable, as per documentation.

-fwhole-program Assume that the current compilation unit represents the whole program being compiled. All public functions and variables with the exception of main and those merged by attribute externally_visible become static functions and in effect are optimized more aggressively by interprocedural optimizers.

So you mast have main defined anywhere in your source files.

like image 80
Sergei Nikulov Avatar answered Oct 01 '22 21:10

Sergei Nikulov