4

If we use __COUNTER__ in two different source files, the value is reset back to zero. Is it possible to make the __COUNTER__ scope global?

File: file1.c

int x=__COUNTER__;

int y=__COUNTER__;

File: file2.c

int a=__COUNTER__;

int b=__COUNTER__;

I would like to have all x, y, a & b to have unique initialized values. In this case, x=a, y=b.


I also tried placing __COUNTER__ in a common Header file. Result is same.

File: common.h

#define VALUE __COUNTER__

replace all __COUNTER__ with VALUE in above files.

Pawan
  • 1,537
  • 1
  • 15
  • 19
Raju Udava
  • 73
  • 3

1 Answers1

3

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.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111