ned14 / pcpp

A C99 preprocessor written in pure Python
Other
220 stars 41 forks source link

__LINE__ reports the line where it's defined, not where it's used #25

Closed Sei-Lisa closed 5 years ago

Sei-Lisa commented 5 years ago

This code:

#ifndef NDEBUG
#define assert(x) do{if(!x)fprintf(stderr,"Assertion failed in file %s line %d: %s",\
__FILE__, __LINE__, #x);}while(0)
#else
#define assert(x)
#endif
assert(0);

results in this output:

#line 7 "assert.c"
do{if(!0)fprintf(stderr,"Assertion failed in file %s line %d: %s","assert.c", 2, "0");}while(0) ;

Note the line number to which __LINE__ expands to is 2, not 7, because its evaluation works by retrieving the line number where the __LINE__ token itself appears, not where it's expanded. This deters about every real use case.

The output with mcpp, gcc and wave is the expected. For example, with gcc:

# 1 "assert.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 31 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 32 "<command-line>" 2
# 1 "assert.c"

do{if(!0)fprintf(stderr,"Assertion failed in file %s line %d: %s","assert.c", 7, "0");}while(0);
ned14 commented 5 years ago

This indeed would be an issue for preprocessor generated unique variable names. Thanks for the BR.

ned14 commented 5 years ago

Ok, give this a try. It's actually subtly broken, but probably nobody will ever notice in real world use cases.

Sei-Lisa commented 5 years ago

Thank you very much, this does solve my use case!