sprajagopal
sprajagopal

Reputation: 350

Retaining and incrementing __COUNTER__ value across a complete make session?

I have an embedded programming language that has syntax similar to C language. It also supports the macro __COUNTER__. I require a particular function to have an incremented argument every time I call it. And this function could be called across multiple files in the project and the values need to be incremented across files. I don't want to manually track the values across files (Or use a common header). I want to use the Counter macro to auto update this argument. My problem is that the macro resets in a new file. Is there any way I can achieve this by

  1. Retaining and incrementing the macro value across the build session?

  2. Or some other entirely new way to do this?

Upvotes: 1

Views: 964

Answers (2)

Matteo Italia
Matteo Italia

Reputation: 126877

If it doesn't need to be evaluated at compile time, but runtime suffices, you could do something like:

// in a .cpp
int global_counter;

And in each relevant function:

extern int global_counter;
const static int counter=global_counter++;
// now in counter you have your value 

counter gets assigned a unique, monotonically increasing, per-function global id (even though this happens at runtime, and the exact value depends on the order of call of the functions). Also notice that, if your program is multithreaded, you'll want to use an std::atomic_int.

Upvotes: 2

vlp
vlp

Reputation: 8116

If you like silly solutions -- here we go. Pretty please do have a confirmed backup of your sources (i.e. test this code on a copy).

To substitute all occurrences of __COUNTER__ with incrementing value, keeping original files in .orig (thanks to @melpomene, I am not into perl):

perl -i.orig -p -e '$a='\''/*GENERATED*/'\''; s/\b__COUNTER__\b/$c++.$a/eg'

To find out the largest value used in substitution (shell):

grep -ho '[1234567890]*/\*GENERATED\*/' *.cpp | cut -d/ -f 1 | sort -n | tail -n 1

Combined solution (shell script):

# Find out the largest value used
MAXUSED=$(grep -ho '[1234567890]*/\*GENERATED\*/' *.cpp | cut -d/ -f 1 | sort | tail -n 1)
# Substitute, starting from MAXUSED+1
perl -i.orig -p -e '$m='"$MAXUSED"'+1; $a='\''/*GENERATED*/'\''; s/\b__COUNTER__\b/(($c++)+$m).$a/eg' *.cpp

Good luck!

Upvotes: 0

Related Questions