Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one pass a code string into a C\C++-macro?

Tags:

c++

c

macros

For example I'd like to make a debug macro which prints a code string before attempting to execute it. I suppose it should look something like that

#define TRACE(string) printf("Trying to execute: %s\n",\"string\"); \
                      string

...

void foo() {
  printf("1\n");
}
void bar() {
  printf("2\n");
}

int main() {
  ...
  foo();
  TRACE(bar(););
  ...
}

With expected output

...
1
Trying to execute: bar();
2
...

Well, THIS is not how one does it: compiler complains about illegal syntax. Is there a way to do it at all?

like image 778
ScalewingedAcidicorn Avatar asked Nov 29 '22 23:11

ScalewingedAcidicorn


1 Answers

You need to use stringification using #:

#define TRACE(string) printf("Trying to execute: %s\n",#string); \
                      string

Full example:

#include <stdio.h>

#define TRACE(string) printf("Trying to execute: %s\n",#string); \
                          string

void foo() {
  printf("1\n");
}
void bar() {
  printf("2\n");
}

int main() {

  foo();
  TRACE(bar(););
}

output:

1
Trying to execute: bar();
2

live example on ideone

like image 103
m.s. Avatar answered Dec 10 '22 16:12

m.s.