View previous topic :: View next topic |
Author |
Message |
E_Blue
Joined: 13 Apr 2011 Posts: 417
|
There's any way to check the size of a define? |
Posted: Tue Feb 20, 2018 6:31 am |
|
|
I have a header file that have some default values and I want to avoid the compilation if one of them is too big in length.
I tried the following code without success
Code: | #define DefaultCode "7777"
#if sizeof(DefaultCode) >4
#error "DefaultCode too big, CHECK CONFIGURATION FILE"
#endif |
_________________ Electric Blue |
|
![](templates/subSilver/images/spacer.gif) |
Ttelmah
Joined: 11 Mar 2010 Posts: 19372
|
|
Posted: Tue Feb 20, 2018 8:00 am |
|
|
A define, does not exist.
It has no size, till you put it into a variable. The variable then has a size.
#DEFINES in C, are text macro substitutions, not variables.
All the #functions are carried out by the pre-processor, before any 'C' even exists. sizeof, is a C function, which hasn't even been loaded yet... |
|
![](templates/subSilver/images/spacer.gif) |
temtronic
Joined: 01 Jul 2010 Posts: 9174 Location: Greensville,Ontario
|
|
Posted: Tue Feb 20, 2018 8:31 am |
|
|
hmm... rainy day here..
I tired this..
...
#define BUFFER_SIZE 17
#if BUFFER_SIZE>16
#error Buffer size is too large
#endif
...
does work, well it compiles and if BUFFER_SIZE is <17 no msg appears.
when it's >16 the error msg appears
if you change
#define DefaultCode "7777"
to
#define DefaultCode 7777
then
#if DefaultCode >7777
#error Check config file
#endif
maybe it'll work ??
If you want to check for DefaultCode being more than 4 space wide, then test for >9999.
like I said rainy day here..slipping on water on ice is NOT fun.
Jay |
|
![](templates/subSilver/images/spacer.gif) |
Ttelmah
Joined: 11 Mar 2010 Posts: 19372
|
|
Posted: Tue Feb 20, 2018 8:59 am |
|
|
Yes. The preprocessor supports arithmetic tests. But that is all.
You can test a numeric value, or it the define itself exists.
No 'strings' or sizes.
So if you made your value a numeric value as opposed to a string, you could refuse it if it was >9999. However it couldn't then contain text like "ABCD". |
|
![](templates/subSilver/images/spacer.gif) |
E_Blue
Joined: 13 Apr 2011 Posts: 417
|
|
Posted: Wed Feb 28, 2018 7:47 am |
|
|
Thanks for your answers.
So I can apply this only to numeric values but not strings.
I guess i will must have care about those strings one by one by my self. _________________ Electric Blue |
|
![](templates/subSilver/images/spacer.gif) |
Ttelmah
Joined: 11 Mar 2010 Posts: 19372
|
|
Posted: Wed Feb 28, 2018 8:03 am |
|
|
In C itself, once you put the define into a variable, you can of course check this.
Code: |
#define FRED "A Value"
char var[]=FRED;
if (strlen(var)>4)
{
}
|
But this is at run time, not compile time.
It is worth pointing out that 'sizeof' wouldn't work anyway. The sizeof a string is the size of the pointer that addresses it.... |
|
![](templates/subSilver/images/spacer.gif) |
|