Compile time variable sized string literal in C - c

What should be done for DD ?
if
#define HEADING_TITLE_PROJECT_NAME "<= Version Maintenance Based On Compiled DateTime =>"
#define SIZE_OF_HEADER_FOR_DECORATION_PURPOSE sizeof(HEADING_TITLE_PROJECT_NAME)
#define DD ????
#define HEADING "\r\n"DD"\r\n"HEADING_TITLE_PROJECT_NAME"\r\n"DD"\r\n"
I want to get HEADING string literal as follows:
<==================================================>
<= Version Maintenance Based On Compiled DateTime =>
<==================================================>
The = sign or anything I put once will repeat within <== ... ==> to fill the HEADING_TITLE_PROJECT_NAME space.
Can it be done this way or other.
I only want to change the HEADING_TITLE_PROJECT_NAME in coding time and nothing else.
JUST THOUGHT IF IT CAN BE DONE
:)
<==Edit start==>
Something like
#define DD\
char * get()\
{\
char arr[100] = '\0';\
for (int i=0; i < SIZE_OF_HEADER_FOR_DECORATION_PURPOSE - 1; i++)\
{\
arr[i] = "=";\
}\
return arr;\
}
<==Edit ends==>

Unfortunately, there's no automatic way to generate DD in the standard C preprocessor, as long as you want to use it the way you use in the definition of HEADING macro.
As long as you insist of having that HEADING defined they way it is currently defined, I can only suggest using a semi-automatic approach :). Define DD manually, explicitly.
#define HEADING_TITLE_PROJECT_NAME "<= Version Maintenance Based On Compiled DateTime =>"
#define DD "<==================================================>"
And then just add
STATIC_ASSERT(sizeof HEADING_TITLE_PROJECT_NAME == sizeof DD);
right under it (with your favorite implementation of STATIC_ASSERT). That way any discrepancy in DD's length will immediately trigger an error and force the developer to update the DD.

This is impossible because of sizeof is evaluated after the preprocessor, rather than before.
If you knew the length of the string in advance, it would be.
Because the proprocessor doesn't have any looping constructs, you wind up creating them. Boost does it something like this
#define REPEAT_TIMES(macro, n) REPEAT##n(macro)
#define REPEAT1(macro) MACRO
#define REPEAT2(macro) REPEAT1(macro)MACRO
#define REPEAT3(macro) REPEAT2(macro)MACRO
....
You would then simply:
#define FILLER "="
#define DD "<"REPEAT_TIMES(FILLER, 34)">"

Your implementation of DD isn't a bad idea, though it suffers from some poor syntax and undefined behavior.
const char *DDD(void)
{
static char arr[] = HEADING_TITLE_PROJECT_NAME;
if(arr[2] == ' ')
for(size_t i = 2; i + 3 < sizeof arr; i++)
arr[i] = '=';
return arr;
}
#define DD DDD()
You can't return a pointer to stack data, so you have to use a static array. We can make sure it's the right size by having it automatically set to the #defined string, then checking if it's been filled with '=' yet and, if not, fill it. Then we return a const pointer to it so that no one tries to modify it.
Your macro defines a function, get, with unspecified arguments, and returning a modifiable char * to stack data. Unfortunately, this function will be defined everywhere you use the macro, which will result in many multiple definition errors.
You can't use this with raw string concatenation, but it will work for everything else you want.

Related

Defining a function as macro

I am trying to understand defining functions as macros and I have the following code, which I am not sure I understand:
#define MAX(i, limit) do \
{ \
if (i < limit) \
{ \
i++; \
} \
} while(1)
void main(void)
{
MAX(0, 3);
}
As I understand it tries to define MAX as an interval between 2 numbers? But what's the point of the infinite loop?
I have tried to store the value of MAX in a variable inside the main function, but it gives me an error saying expected an expression
I am currently in a software developing internship, and trying to learn embedded C since it's a new field for me. This was an exercise asking me what the following code will do. I was confused since I had never seen a function written like this
You are confused because this is a trick question. The posted code makes no sense whatsoever. The MAX macro expands indeed to an infinite loop and since its first argument is a literal value, i++ expands to 0++ which is a syntax error.
The lesson to be learned is: macros are confusing, error prone and should not be used to replace functions.
You have to understand that before your code gets to compiler, first it goes through a preprocessor. And it basically changes your text-written code. The way it changes the code is controlled with preprocessor directives (lines that begin with #, e.g. #include, #define, ...).
In your case, you use a #define directive, and everywhere a preprocessor finds a MAX(i, limit) will be replaced with its definition.
And the output of a preprocessor is also a textual file, but a bit modified. In your case, a preprocessor will replace MAX(0, 3) with
do
{
if (0 < 3)
{
0++;
}
} while(1)
And now the preprocessor output goes to a compiler like that.
So writing a function in a #define is not the same as writing a normal function void max(int i, int limit) { ... }.
Suppose you had a large number of statements of the form
if(a < 10) a++;
if(b < 100) b++;
if(c < 1000) c++;
In a comment, #the busybee refers to this pattern as a "saturating incrementer".
When you see a repeated pattern in code, there's a natural inclination to want to encapsulate the pattern somehow. Sometimes this is a good idea, or sometimes it's fine to just leave the repetition, if the attempt to encapsulate it ends up making things worse.
One way to encapsulate this particular pattern — I'm not going to say whether I think it's a good way or not — would be to define a function-like macro:
#define INCR_MAX(var, max) if(var < max) var++
Then you could say
INCR_MAX(a, 10);
INCR_MAX(b, 100);
INCR_MAX(c, 1000);
One reason to want to make this a function-like macro (as opposed to a true function) is that a macro can "modify its argument" — in this case, whatever variable name you hand to it as var — in a way that a true function couldn't. (That is, if your saturating incrementer were a true function, you would have to call it either as incr_max(&a, 10) or a = incr_max(a, 10), depending on how you chose to set it up.)
However, there's an issue with function-like macros and the semicolon at the end. I'm not going to explain that whole issue here; there's a big long previous SO question about it.
Applying the lesson of that other question, an "improved" INCR_MAX macro would be
#define INCR_MAX(var, max) do { if(var < max) var++; } while(0)
Finally, it appears that somewhere between your exercise and this SO question, the while(0) at the end somehow got changed to while(1). This just about has to have been an unintentional error, since while(1) makes no sense in this context whatsoever.
Yeah, there's a reason you don't understand it - it's garbage.
After preprocessing, the code is
void main(void)
{
do
{
if ( 0 < 3 )
{
0++;
}
} while(1);
}
Yeah, no clue what this thing is supposed to do. The name MAX implies that it should evaluate to the larger of its two arguments, a la
#define MAX(a,b) ((a) < (b) ? (b) : (a))
but that's obviously not what it's doing. It's not defining an interval between two numbers, it's attempting to set the value of the first argument to the second, but in a way that doesn't make a lick of sense.
There are three problems (technically, four):
the compiler will yak on 0++ - a constant cannot be the operand of the ++ or -- operators;
If either i or limit are expressions, such as MAX(i+1, i+5) you're going to have the same problem with the ++ operator and you're going to have precedence issues;
assuming you fix those problems, you still have an infinite loop;
The (technical) fourth problem is ... using a macro as a function. I know, this is embedded world, and embedded world wants to minimize function call overhead. That's what the inline function specifier is supposed to buy you so you don't have to go through this heartburn.
But, okay, maybe the compiler available for the system you're working on doesn't support inline so you have to go through this exercise.
But you're going to have to go to the person who gave you this code and politely and respectfully ask, "what is this crap?"

Renaming a macro in C

Let's say I have already defined 9 macros from
ABC_1 to ABC_9
If there is another macro XYZ(num) whose objective is to call one of the ABC_{i} based on the value of num, what is a good way to do this? i.e. XYZ(num) should call/return ABC_num.
This is what the concatenation operator ## is for:
#define XYZ(num) ABC_ ## num
Arguments to macros that use concatenation (and are used with the operator) are evaluated differently, however (they aren't evaluated before being used with ##, to allow name-pasting, only in the rescan pass), so if the number is stored in a second macro (or the result of any kind of expansion, rather than a plain literal) you'll need another layer of evaluation:
#define XYZ(num) XYZ_(num)
#define XYZ_(num) ABC_ ## num
In the comments you say that num should be a variable, not a constant. The preprocessor builds compile-time expressions, not dynamic ones, so a macro isn't really going to be very useful here.
If you really wanted XYZ to have a macro definition, you could use something like this:
#define XYZ(num) ((int[]){ \
0, ABC_1, ABC_2, ABC_3, ABC_4, ABC_5, ABC_6, ABC_7, ABC_8, ABC_9 \
}[num])
Assuming ABC_{i} are defined as int values (at any rate they must all be the same type - this applies to any method of dynamically selecting one of them), this selects one with a dynamic num by building a temporary array and selecting from it.
This has no obvious advantages over a completely non-macro solution, though. (Even if you wanted to use macro metaprogramming to generate the list of names, you could still do that in a function or array definition.)
Yes, that's possible, using concatenation. For example:
#define FOO(x, y) BAR ##x(y)
#define BAR1(y) "hello " #y
#define BAR2(y) int y()
#define BAR3(y) return y
FOO(2, main)
{
puts(FOO(1, world));
FOO(3, 0);
}
This becomes:
int main()
{
puts("hello " "world");
return 0;
}

Iteration through defines

I'm working in a C program and I came across a problem. I have this
#define NUMBER_OF_OPTIONS 5
#define NAME_OPTION1 "Partida Rapida"
#define NAME_OPTION2 "Elige Nivel"
#define NAME_OPTION3 "Ranking"
#define NAME_OPTION4 "Creditos"
#define NAME_OPTION5 "Exit"
for (iterator = 1; iterator <= NUMBER_OF_OPTIONS; iterator++){
menu_options[iterator-1]= NAME_OPTION + iterator
}
I want that "NAME_OPTION + iterator" takes the value of the corresponding #define. For example if the variable "iterator" is equal to one, I want menu_options[iterator-1] to take the value of NAME_OPTION1, which is "Partida Rapida".
How can I get this?
Essentially, you can't. #define macros are handled by the C Preprocessor and do textual substitution wherever that macro appears in the code. The macro NAME_OPTION has not been defined, so the compiler should complain. C does not allow appending numbers onto strings, or especially onto symbols like NAME_OPTION. Use an array of const char*, which you can then refer to with your iterator.
You can't use defines as this, you can do:
const char *menu_options[5] = {
"Partida Rapida",
"Elige Nivel",
"Ranking",
"Creditos",
"Exit"
};
If you use #define macro, you just tell preprocessor to replace every occurence of defined word by something else before the code is compiled into machine code.
In this case NUMBER_OF_OPTIONS will be replaced by 5, but there's no occurence of NAME_OPTION*, so nothing will be replaced and you'll probably get an error while preprocessing.
Piere's solutions shows how to do it, but I highly doubt that there's an iterator over char *array, so you have to iterate over given array using an integer index.

Using macro to check null values

My C code contains many functions with pointers to different structs as parameters which shouldn't be NULL pointers. To make my code more readable, I decided to replace this code:
if(arg1==NULL || arg2==NULL || arg3==NULL...) {
return SOME_ERROR;
}
With that macro:
NULL_CHECK(arg1,arg2,...)
How should I write it, if the number of args is unknown and they can point to different structs? (I work in C99)
IMO the most maintainable solution is to write multiple separate calls rather than trying to get "clever" about it.
for example, Win32 programmers use a VERIFY macro which runs an assertion at debug time (the macro ensures that the assertions are stripped out of release code); It's not unusual to see functions which start like this:
int foo(void* arg1, char* str, int n)
{
VERIFY( arg1 != NULL );
VERIFY( str != NULL );
VERIFY( n > 0 );
Obviously, you could very easily condense those 3 lines into a single line, but the macro works best when you don't. If you put them onto separate lines, then a failed assertion will tell you which of the three conditions have not been met, whereas putting them all in the same statement only tells you that something has failed, leavng you to figure out the rest.
If you decide to use a macro, then I recommend using a macro that takes a single argument:
#define NULL_CHECK(val) if (val == NULL) return SOME_ERROR;
You can then write:
NULL_CHECK(s1.member1);
NULL_CHECK(p2->member2);
Etc. One of the advantages is that you can incorporate error reporting or logging accurately to identify the first invalid member like this. With a single composite condition, you only know that at least one of them is invalid, but not exactly which one.
If you must deal with a variable number of arguments, then you need to investigate Boost::Preprocessor, which will work in C as well as C++.
Not that I think it's a great idea to hide a return statement inside a macro, but such a macro could be written like:
#define NULL_CHECK(...) \
do { \
void *_p[] = { __VA_ARGS__ }; \
int _i; \
for (_i = 0; _i < sizeof(_p)/sizeof(*_p); _i++) { \
if (_p[_i] == NULL) { \
return SOME_ERROR; \
} \
} \
} while(0)
Basically, expand the varargs into an array and loop over the indexes.

How can I use "sizeof" in a preprocessor macro?

Is there any way to use a sizeof in a preprocessor macro?
For example, there have been a ton of situations over the years in which I wanted to do something like:
#if sizeof(someThing) != PAGE_SIZE
#error Data structure doesn't match page size
#endif
The exact thing I'm checking here is completely made up - the point is, I often like to put in these types of (size or alignment) compile-time checks to guard against someone modifying a data-structure which could misalign or re-size things which would break them.
Needless to say - I don't appear to be able to use a sizeof in the manner described above.
There are several ways of doing this.
Following snippets will produce no code if sizeof(someThing) equals PAGE_SIZE; otherwise they will produce a compile-time error.
1. C11 way
Starting with C11 you can use static_assert (requires #include <assert.h>).
Usage:
static_assert(sizeof(someThing) == PAGE_SIZE, "Data structure doesn't match page size");
2. Custom macro
If you just want to get a compile-time error when sizeof(something) is not what you expect, you can use following macro:
#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
Usage:
BUILD_BUG_ON( sizeof(someThing) != PAGE_SIZE );
This article explains in details why it works.
3. MS-specific
On Microsoft C++ compiler you can use C_ASSERT macro (requires #include <windows.h>), which uses a trick similar to the one described in section 2.
Usage:
C_ASSERT(sizeof(someThing) == PAGE_SIZE);
Is there anyway to use a "sizeof" in a pre-processor macro?
No. The conditional directives take a restricted set of conditional expressions; sizeof is one of the things not allowed.
Preprocessing directives are evaluated before the source is parsed (at least conceptually), so there aren't any types or variables yet to get their size.
However, there are techniques to getting compile-time assertions in C (for example, see this page).
I know it's a late answer, but to add on to Mike's version, here's a version we use that doesn't allocate any memory. I didn't come up with the original size check, I found it on the internet years ago and unfortunately can't reference the author. The other two are just extensions of the same idea.
Because they are typedef's, nothing is allocated. With the __LINE__ in the name, it's always a different name so it can be copied and pasted where needed. This works in MS Visual Studio C compilers, and GCC Arm compilers. It does not work in CodeWarrior, CW complains about redefinition, not making use of the __LINE__ preprocessor construct.
//Check overall structure size
typedef char p__LINE__[ (sizeof(PARS) == 4184) ? 1 : -1];
//check 8 byte alignment for flash write or similar
typedef char p__LINE__[ ((sizeof(PARS) % 8) == 0) ? 1 : 1];
//check offset in structure to ensure a piece didn't move
typedef char p__LINE__[ (offsetof(PARS, SUB_PARS) == 912) ? 1 : -1];
I know this thread is really old but...
My solution:
extern char __CHECK__[1/!(<<EXPRESSION THAT SHOULD COME TO ZERO>>)];
As long as that expression equates to zero, it compiles fine. Anything else and it blows up right there. Because the variable is extern'd it will take up no space, and as long as no-one references it (which they won't) it won't cause a link error.
Not as flexible as the assert macro, but I couldn't get that to compile in my version of GCC and this will... and I think it will compile just about anywhere.
The existing answers just show how to achieve the effect of "compile-time assertions" based on the size of a type. That may meet the OP's needs in this particular case, but there are other cases where you really need a preprocessor conditional based on the size of a type. Here's how to do it:
Write yourself a little C program like:
/* you could call this sizeof_int.c if you like... */
#include <stdio.h>
/* 'int' is just an example, it could be any other type */
int main(void) { printf("%zd", sizeof(int); }
Compile that. Write a script in your favorite scripting language, which runs the above C program and captures its output. Use that output to generate a C header file. For example, if you were using Ruby, it might look like:
sizeof_int = `./sizeof_int`
File.open('include/sizes.h','w') { |f| f.write(<<HEADER) }
/* COMPUTER-GENERATED, DO NOT EDIT BY HAND! */
#define SIZEOF_INT #{sizeof_int}
/* others can go here... */
HEADER
Then add a rule to your Makefile or other build script, which will make it run the above script to build sizes.h.
Include sizes.h wherever you need to use preprocessor conditionals based on sizes.
Done!
(Have you ever typed ./configure && make to build a program? What configure scripts do is basically just like the above...)
What about next macro:
/*
* Simple compile time assertion.
* Example: CT_ASSERT(sizeof foo <= 16, foo_can_not_exceed_16_bytes);
*/
#define CT_ASSERT(exp, message_identifier) \
struct compile_time_assertion { \
char message_identifier : 8 + !(exp); \
}
For example in comment MSVC tells something like:
test.c(42) : error C2034: 'foo_can_not_exceed_16_bytes' : type of bit field too small for number of bits
Just as a reference for this discussion, I report that some compilers get sizeof() ar pre-processor time.
JamesMcNellis answer is correct, but some compilers go through this limitation (this probably violates strict ansi c).
As a case of this, I refer to IAR C-compiler (probably the leading one for professional microcontroller/embedded programming).
#define SIZEOF(x) ((char*)(&(x) + 1) - (char*)&(x)) might work
In C11 _Static_assert keyword is added. It can be used like:
_Static_assert(sizeof(someThing) == PAGE_SIZE, "Data structure doesn't match page size")
In my portable c++ code ( http://www.starmessagesoftware.com/cpcclibrary/ ) wanted to put a safe guard on the sizes of some of my structs or classes.
Instead of finding a way for the preprocessor to throw an error ( which cannot work with sizeof() as it is stated here ), I found a solution here that causes the compiler to throw an error.
http://www.barrgroup.com/Embedded-Systems/How-To/C-Fixed-Width-Integers-C99
I had to adapt that code to make it throw an error in my compiler (xcode):
static union
{
char int8_t_incorrect[sizeof( int8_t) == 1 ? 1: -1];
char uint8_t_incorrect[sizeof( uint8_t) == 1 ? 1: -1];
char int16_t_incorrect[sizeof( int16_t) == 2 ? 1: -1];
char uint16_t_incorrect[sizeof(uint16_t) == 2 ? 1: -1];
char int32_t_incorrect[sizeof( int32_t) == 4 ? 1: -1];
char uint32_t_incorrect[sizeof(uint32_t) == 4 ? 1: -1];
};
After trying out the mentioned macro's, this fragment seems to produce the desired result (t.h):
#include <sys/cdefs.h>
#define STATIC_ASSERT(condition) typedef char __CONCAT(_static_assert_, __LINE__)[ (condition) ? 1 : -1]
STATIC_ASSERT(sizeof(int) == 4);
STATIC_ASSERT(sizeof(int) == 42);
Running cc -E t.h:
# 1 "t.h"
...
# 2 "t.h" 2
typedef char _static_assert_3[ (sizeof(int) == 4) ? 1 : -1];
typedef char _static_assert_4[ (sizeof(int) == 42) ? 1 : -1];
Running cc -o t.o t.h:
% cc -o t.o t.h
t.h:4:1: error: '_static_assert_4' declared as an array with a negative size
STATIC_ASSERT(sizeof(int) == 42);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
t.h:2:84: note: expanded from macro 'STATIC_ASSERT'
...typedef char __CONCAT(_static_assert_, __LINE__)[ (condition) ? 1 : -1]
^~~~~~~~~~~~~~~~~~~~
1 error generated.
42 isn't the answer to everything after all...
To check at compile time the size of data structures against their constraints I've used this trick.
#if defined(__GNUC__)
{ char c1[sizeof(x)-MAX_SIZEOF_X-1]; } // brakets limit c1's scope
#else
{ char c1[sizeof(x)-MAX_SIZEOF_X]; }
#endif
If x's size is greater or equal than it's limit MAX_SIZEOF_X, then the gcc wil complain with a 'size of array is too large' error. VC++ will issue either error C2148 ('total size of array must not exceed 0x7fffffff bytes') or C4266 'cannot allocate an array of constant size 0'.
The two definitions are needed because gcc will allow a zero-sized array to be defined this way (sizeof x - n).
The sizeof operator is not available for the preprocessor, but you can transfer sizeof to the compiler and check the condition in runtime:
#define elem_t double
#define compiler_size(x) sizeof(x)
elem_t n;
if (compiler_size(elem_t) == sizeof(int)) {
printf("%d",(int)n);
} else {
printf("%lf",(double)n);
}

Resources