0

Is it possible to create a macro that count lines with the option to the macro value "in advance" for example:

START_COUNT_MACRO
CMD1
CMD2
CMD3 (COUNTER_VALUE) // needs to be 5 for this example
CMD4
CMD5
END_COUNT_MACRO

the number of CMD commands can change. since it's an ongoing development, and also will be easier for maintenance since you don't need to update the Counter value each time. I tried using this Count source file lines using macros? solution, but it couldn't be done since it define variables that don't exist when evaluating CMD3. Do you know another trick that could be used to help me?

iMoyal
  • 16
  • 3
  • I see two options: 1. Use the preprocessor, as suggested. The syntax will then be something like `COUNT_MACRO( CMD CMD COUNTER_VALUE CMD CMD )`. You'll get your value at compile-time, but the downside is that `COUNT_MACRO` expands to a single long line (even if you have line-breaks in parentheses), so a debugger won't be able to debug the code line by line. 2. Or you can use templates, but then the value would only be accessible at runtime. Which one sounds better? – HolyBlackCat Dec 12 '21 at 19:08
  • 3
    Please consider whether this might be a https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem I.e. think whether you prefer help with something else, which you believe to solve by finding this macro magic. – Yunnosch Dec 12 '21 at 19:16
  • I don't understand this question nor what you're asking for. – Gabriel Staples Dec 12 '21 at 19:19
  • added some clarifications – iMoyal Dec 13 '21 at 06:31
  • Is it OK for you if START_COUNT and END_COUNT are outside any function? – Yunnosch Dec 13 '21 at 06:56
  • The preprocessor of C is a very limited beast. You might want to use some other generic preprocessor like "M4" as an additional step before calling your compiler. – the busybee Dec 13 '21 at 08:51

1 Answers1

0

This is as close as I can get.
It requires START_COUNT and END_COUNT to be outside of functions.

#include <stdio.h>

extern const int COUNT;
static const int BEFORE = __LINE__;
int main(void)
{
    printf("Hello, World! %d\n", COUNT); // analog to CMD3 (COUNTER_VALUE)
    return 0;
}
static const int AFTER = __LINE__;
const int COUNT = AFTER - BEFORE - 1;
Yunnosch
  • 26,130
  • 9
  • 42
  • 54