You can compile your project so that each file has an individual offset (big enough, like 100) to __COUNTER__
and use that offset to have individual counters.
==> file1.c <==
int x = COUNTER;
int y = COUNTER;
==> file2.c <==
int a = COUNTER;
int b = COUNTER;
==> main.c <==
#include <stdio.h>
extern int a, b, x, y;
int main() {
printf("%d %d %d %d\n", a, b, x, y);
}
Such project configured with CMake with:
cmake_minimum_required(VERSION 3.11)
project(test)
file(GLOB srcs *.c)
set(ii 0)
foreach(ff IN LISTS srcs)
set_source_files_properties(${ff} PROPERTIES COMPILE_DEFINITIONS
# add an offset to each file
COUNTER_OFFSET=${ii}
)
# increment is by 100
math(EXPR ii "${ii} + 100")
endforeach()
add_compile_definitions(
# add COUNTER definition with the offset
"COUNTER=(__COUNTER__+COUNTER_OFFSET)"
)
add_executable(test ${srcs})
So that each file has a separate unique offset, and COUNTER
epxands to __COUNTER__ + some offset
:
[1/4] /usr/bin/cc -DCOUNTER="(__COUNTER__+COUNTER_OFFSET)" -DCOUNTER_OFFSET=100 ...
[2/4] /usr/bin/cc -DCOUNTER="(__COUNTER__+COUNTER_OFFSET)" -DCOUNTER_OFFSET=200 ...
[3/4] /usr/bin/cc -DCOUNTER="(__COUNTER__+COUNTER_OFFSET)" -DCOUNTER_OFFSET=0 ...
The program outputs:
$ bin/test
100 101 0 1
You could track how many times each file uses COUNTER
with a regex, and then increment the offset only by the number of times COUNTER
was used in the file, hopefully creating some limited continuous counting.