C Macro Wizardry for multiplying a statement N times - c

I have the following macros that take a statement and multiply it
#define X2(s) do { s; s; } while (0)
#define X3(s) do { s; s; s; } while (0)
#define X4(s) do { s; s; s; s; } while (0)
#define X5(s) do { s; s; s; s; s; } while (0)
#define X6(s) do { s; s; s; s; s; s; } while (0)
etc.
so the pre-processor expands
X2(i++)
to
do { i++; i++; } while (0)
I would like to have a macro
#define CODE_MULTIPLIER(x,s)
which expands a statement s, x times. so
CODE_MULTIPLIER(3,j--)
would be expanded to
do { j--; j--; j--; } while (0)
The ugly idea i came up with is:
#define CODE_MULTIPLIER(x,s) do { \
if ((x) == 1) { s; } \
else if ((x) == 2) { s; s; } \
else if ((x) == 3) { s; s; s; } \
else if ((x) == 4) { s; s; s; s; } \
else if ((x) == 5) { s; s; s; s; s; } \
etc. \
else assert(0); \
} while (0)
hoping the compiler will optimize out the ifs
Why would you ever want macros like this?
One reason (but not the only one) is the need for exact delays in embedded programming. using while/for loops slightly change the timing. Compiler optimization of loops may not preserve delicate timing requirements.
Here is a typical usage example:
#define CLOCK_FREQ_Hz (16000000L)
#define US_TO_NOPS(us) ((us) * CLOCK_FREQ_Hz / 1000000L)
#define OFF_ON_DELAY_US (4) // units: microseconds
#define ON_OFF_DELAY_US (2) // units: microseconds
#define OFF_ON_DELAY_NOPS US_TO_NOPS(OFF_ON_DELAY_US) // units: instructions
#define ON_OFF_DELAY_NOPS US_TO_NOPS(ON_OFF_DELAY_US) // units: instructions
PIN = OFF;
CODE_MULTIPLIER(OFF_ON_DELAY_NOPS,asm("nop")); // 4us delay
PIN = ON;
CODE_MULTIPLIER(ON_OFF_DELAY_NOPS,asm("nop")); // 2us delay
PIN = OFF;
I would appreciate any suggestions as to how to create this macro. High preference to compiler-independent macro wizardry (Us embedded dudes don't always have the luxury of using GCC)
Thanx

Yes such things are possible if you don't stretch things too much. P99 has a whole series of macros to accomplish different sorts of such unrolling. An easy one here would be
#define toto(I) f(I)
P99_UNROLL(toto, 3); // => f(0); f(1); f(2);
But beware that for using P99 you'd need a compiler that implements C99 compliant preprocessor.

As recursion cannot be generally used in macros, and you may not have "extended unrolling features" the only way to have a "always valid solution" is to do some manual work like following one:
#define X1(s) do { s;} while (0)
#define X2(s) do { s; s; } while (0)
#define X3(s) do { s; s; s; } while (0)
#define X4(s) do { s; s; s; s; } while (0)
#define X5(s) do { s; s; s; s; s; } while (0)
#define X6(s) do { s; s; s; s; s; s; } while (0)
#define CODE_MULTIPLIER(s, i) X##i(s)
And you just use CODE_MULTIPLIER(s, i) in your code. In this way you avoid the if/else if conditional expressions. For example you will use CODE_MULTIPLIER(i++,3).
Another trick can be applied if you aren't going to use X1,X2.... but only CODE_MULTIPLIER(s,i):
#define X1(s) s
#define X2(s) s; X1(s)
#define X3(s) s; X2(s)
#define X4(s) s; X3(s)
#define X5(s) s; X4(s)
#define X6(s) s; X5(s)
#define CODE_MULTIPLIER(s, i) do { X##i(s); } while (0)
which has a nicer sintax.

Related

How to use C macro for both numbers and strings?

if (termAttributes.c_lflag & OPOST)
puts("c_lflag = OPOST");
if (termAttributes.c_lflag & OLCUC)
puts("c_lflag = OLCUC");
I have some code like the above. I want to simplify it as something like this.
TCFLAGPRINT(termAttributes, c_lflag, OPOST)
TCFLAGPRINT(termAttributes, c_lflag, OLCUC)
Could anybody show how to define TCFLAGPRINT?
Here is one way to do it:
#define TCFLAGPRINT(tio, field, flag) \
do { \
if ((tio).field & (flag)) \
puts(#field " = " #flag); \
} while (0)
The do { } while (0) wrapper is a common idiom that forces you to add a semicolon to the end of the macro call. (In this case, it also prevents you adding else after the macro call.)
The # operator before a macro parameter name in the replacement text of the function-like macro converts the parameter name to a string literal.
The #field " = " #flag is concatenating three string literals into a single string constant.
I print bit masks quite a lot so I've come up with my own mechanism for this.
I use a struct table and some functions.
I've pulled in some of my code from a library to illustrate:
#include <stdio.h>
#include <string.h>
#include <termios.h>
typedef struct {
unsigned long tgb_val;
const char *tgb_tag;
const char *tgb_reason;
} tgb_t;
#define TGBEOT \
{ .tgb_tag = NULL }
#define TGBMORE(_tgb) \
_tgb->tgb_tag != NULL
#define _TGBFORALL(_tgb) \
; TGBMORE(_tgb); ++_tgb
#define TGBFORALL(_tga,_tgb) \
_tgb = _tga; TGBMORE(_tgb); ++_tgb
#define TGBDUAL(_sym) \
{ .tgb_val = _sym, .tgb_tag = #_sym },
tgb_t lflag_tgb[] = {
TGBDUAL(OPOST)
TGBDUAL(OLCUC)
TGBEOT
};
// tgbmskdcd -- decode mask value
char *
tgbmskdcd(char *buf,const tgb_t *tgb,unsigned long val)
{
const char *tag;
int sep;
char *bp;
int len;
bp = buf;
*bp = 0;
sep = 0;
for (TGBFORALL(tgb,tgb)) {
if ((val & tgb->tgb_val) == 0)
continue;
if (sep)
*bp++ = ' ';
sep = 1;
tag = tgb->tgb_tag;
len = strlen(tag);
strcpy(bp,tag);
bp += len;
}
return buf;
}
int
main(void)
{
struct termios term;
char buf[100];
tcgetattr(1,&term);
printf("c_lflag: %s\n",tgbmskdcd(buf,lflag_tgb,term.c_lflag));
return 0;
}
Here's the output:
c_lflag: OPOST OLCUC

Macro issue for timing

I am searching a nice way to create a "no action" timing (CPU useless operation for timing).
To explain my issue here is the code that I want to change to a macro :
int main (void)
{
int i=0;
printf("Start\r\n");
for(i=0;i<1000;i++); //LINE TO CHANGE TO A MACRO
printf("Delayed trace\r\n");
return 0;
}
Do you have any idea ?
Thanks by advance.
General way for defining such a macro would be:
#define DELAY(amount) \
do { \
/* method of delay */ \
} while (0)
In your case:
#define DELAY(amount) \
do { \
int i; \
for (i = 0; i < amount; ++i); \
} while (0)
If you wish to introduce a delay in terms of some loop iterations, you could employ
#define INTRODUCE_DELAY(count) for(int i = 0; i < count; i++);
You could modify this through a compiler switch to invoke a sleep of similar us as shown below. In case you can't declare i in the for loop then, we can define a small function (which could potentially be inline as shown below
#ifdef WIN32
void mysleep(int count)
{
int i;
for(i = 0; i < count; i++);
}
#define INTRODUCE_DELAY(count) mysleep(count);
#else
#define INTRODUCE_DELAY(count) sleep(count);
#endif
I think you need sleep function, (Work only on unix/linux though)
#include <unistd.h>
#define DELAY(SEC) sleep(SEC)
There must be a similar function in windows.

Thread execution time in C/Linux

Wandering if I can measure actual time or cpu ticks taken by a particular thread.
pthreadcreate(.........);
//
//
pthreadjoin(.......);
I am running with 3 threads.
One master thread is calling the rest two threads.
I want to measure the execution time for a called thread.
what should I use in linux environment ?
you can do one thing
In thread function at start up make a log using printk. You can separate it with different thread printing with it thread_t variable or thread index
and at end of that thread function put another log like that.
So in dmesg
will shows the log with timestamp
so you can differentiate end log time with start log time.
I know this is not more practical way of doing this but just for debugging purpose you can do this without much effort.
If you want to have a more accurate result you can use tick counters :
#ifndef TIMING_H
#define TIMING_H
/*
* -- Init timing library with timing_init();
* -- get timestamp :
* tick_t t;
* GET_TICK(t);
* -- get delay between two timestamps in microseconds :
* TIMING_DELAY(t1, t2);
*/
#include <sys/time.h>
#include <unistd.h>
#include <stdint.h>
#ifndef min
#define min(a,b) \
({__typeof__ ((a)) _a = (a); \
__typeof__ ((b)) _b = (b); \
_a < _b ? _a : _b; })
#endif
typedef union u_tick
{
uint64_t tick;
struct
{
uint32_t low;
uint32_t high;
}
sub;
} tick_t;
static double scale_time = 0.0;
static unsigned long long residual = 0;
#if defined(__i386__) || defined(__pentium__) || defined(__pentiumpro__) || defined(__i586__) || defined(__i686__) || defined(__k6__) || defined(__k7__) || defined(__x86_64__)
# define GET_TICK(t) __asm__ volatile("rdtsc" : "=a" ((t).sub.low), "=d" ((t).sub.high))
#else
# error "Unsupported processor"
#endif
#define TICK_RAW_DIFF(t1, t2) ((t2).tick - (t1).tick)
#define TICK_DIFF(t1, t2) (TICK_RAW_DIFF(t1, t2) - residual)
#define TIMING_DELAY(t1, t2) tick2usec(TICK_DIFF(t1, t2))
void timing_init(void)
{
static tick_t t1, t2;
int i;
residual = (unsigned long long)1 << 63;
for(i = 0; i < 20; i++)
{
GET_TICK(t1);
GET_TICK(t2);
residual = min(residual, TICK_RAW_DIFF(t1, t2));
}
{
struct timeval tv1,tv2;
GET_TICK(t1);
gettimeofday(&tv1,0);
usleep(500000);
GET_TICK(t2);
gettimeofday(&tv2,0);
scale_time = ((tv2.tv_sec*1e6 + tv2.tv_usec) -
(tv1.tv_sec*1e6 + tv1.tv_usec)) /
(double)(TICK_DIFF(t1, t2));
}
}
double tick2usec(long long t)
{
return (double)(t)*scale_time;
}
#endif /* TIMING_H */

Printing name of #define by its value?

I have a C program with some definitions for error codes. Like this:
#define FILE_NOT_FOUND -2
#define FILE_INVALID -3
#define INTERNAL_ERROR -4
#define ...
#define ...
Is it possible to print the name of the definition by its value? Like this:
PRINT_NAME(-2);
// output
FILE_NOT_FOUND
In short, no. The easiest way to do this would be something like so (PLEASE NOTE: this assumes that you can never have an error assigned to zero/null):
//Should really be wrapping numerical definitions in parentheses.
#define FILE_NOT_FOUND (-2)
#define FILE_INVALID (-3)
#define INTERNAL_ERROR (-4)
typdef struct {
int errorCode;
const char* errorString;
} errorType;
const errorType[] = {
{FILE_NOT_FOUND, "FILE_NOT_FOUND" },
{FILE_INVALID, "FILE_INVALID" },
{INTERNAL_ERROR, "INTERNAL_ERROR" },
{NULL, "NULL" },
};
// Now we just need a function to perform a simple search
int errorIndex(int errorValue) {
int i;
bool found = false;
for(i=0; errorType[i] != NULL; i++) {
if(errorType[i].errorCode == errorValue) {
//Found the correct error index value
found = true;
break;
}
}
if(found) {
printf("Error number: %d (%s) found at index %d",errorType[i].errorCode, errorType[i].errorString, i);
} else {
printf("Invalid error code provided!");
}
if(found) {
return i;
} else {
return -1;
}
}
Enjoy!
Additionally, if you wanted to save on typing even more, you could use a preprocessor macro to make it even neater:
#define NEW_ERROR_TYPE(ERR) {ERR, #ERR}
const errorType[] = {
NEW_ERROR_TYPE(FILE_NOT_FOUND),
NEW_ERROR_TYPE(FILE_INVALID),
NEW_ERROR_TYPE(INTERNAL_ERROR),
NEW_ERROR_TYPE(NULL)
};
Now you only have to type the macro name once, reducing the chance of typos.
You can do something like this.
#include <stdio.h>
#define FILE_NOT_FOUND -2
#define FILE_INVALID -3
#define INTERNAL_ERROR -4
const char* name(int value) {
#define NAME(ERR) case ERR: return #ERR;
switch (value) {
NAME(FILE_NOT_FOUND)
NAME(FILE_INVALID)
NAME(INTERNAL_ERROR)
}
return "unknown";
#undef NAME
}
int main() {
printf("==== %d %s %s\n", FILE_NOT_FOUND, name(FILE_NOT_FOUND), name(-2));
}
No, that's not possible. What would this print?
#define FILE_NOT_FOUND 1
#define UNIT_COST 1
#define EGGS_PER_RATCHET 1
PRINT_NAME(1);
Kinda ...
#define ERROR_CODE_1 "FILE_NOT_FOUND"
#define ERROR_CODE_2 "FILE_FOUND"
#define PRINT_NAME(N) ERROR_CODE_ ## N
or:
static char* error_codes(int err) {
static char name[256][256] = {
};
int base = .... lowest error code;
return name[err - base];
}
#define PRINT_NAME(N) error_code(N)
Why not elect to use an enumeration instead?
enum errors {FILE_NOT_FOUND = -2, FILE_INVALID = -3, INTERNAL_ERROR = -4};
FILE *fp = fopen("file.txt", "r");
if(fp == NULL) {
printf("Error\n");
exit(FILE_NOT_FOUND);
}
Not automatically. The name is losing during compilation, and only the constant number remains in the code.
But you can build something like this:
const char * a[] = {"","","FILE_NOT_FOUND","FILE_INVALID"};
and access it by using the define value absolute value as index.
Use designated initializers of C99 for this, but a bit of care is necessary if your error codes are negative.
First a version for positive values:
#define CODE(C) [C] = #C
static
char const*const codeArray[] = {
CODE(EONE),
CODE(ETWO),
CODE(ETHREE),
};
enum { maxCode = (sizeof codeArray/ sizeof codeArray[0]) };
This allocates an array with the length that you need and with the string pointers at the right positions. Note that duplicate values are allowed by the standard, the last one would be the one that is actually stored in the array.
To print an error code, you'd have to check if the index is smaller than maxCode.
If your error codes are always negative you'd just have to negate the code before printing. But it is probably a good idea to do it the other way round: have the codes to be positive and check a return value for its sign. If it is negative the error code would be the negation of the value.
This is how I do it in C:
< MyDefines.h >
#pragma once
#ifdef DECLARE_DEFINE_NAMES
// Switch-case macro for getting defines names
#define BEGIN_DEFINE_LIST const char* GetDefineName (int key) { switch (key) {
#define MY_DEFINE(name, value) case value: return #name;
#define END_DEFINE_LIST } return "Unknown"; }
#else
// Macros for declaring defines
#define BEGIN_COMMAND_LIST /* nothing */
#define MY_DEFINE(name, value) static const int name = value;
#define END_COMMAND_LIST /* nothing */
#endif
// Declare your defines
BEGIN_DEFINE_LIST
MY_DEFINE(SUCCEEDED, 0)
MY_DEFINE(FAILED, -1)
MY_DEFINE(FILE_NOT_FOUND, -2)
MY_DEFINE(INVALID_FILE, -3)
MY_DEFINE(INTERNAL_ERROR -4)
etc...
END_DEFINE_LIST
< MyDefineInfo.h >
#pragma once
const char* GetDefineName(int key);
< MyDefineInfo.c >
#define DECLARE_DEFINE_NAMES
#include "MyDefines.h"
Now, you can use the declared switch-case macro wherever like this:
< WhereEver.c >
#include "MyDefines.h"
#include "MyDefineInfo.h"
void PrintThings()
{
Print(GetDefineName(SUCCEEDED));
Print(GetDefineName(INTERNAL_ERROR));
Print(GetDefineName(-1);
// etc.
}

C preprocessor macro for returning a string repeated a certain number of times

Does someone know of any C99 preprocessor magic that allows for creating a string consisting of another string repeated N times?
E.g.
STRREP( "%s ", 3 )
becomes
"%s %s %s "
after preprocessing.
The only thing I could think of myself was something like this
#define STRREP( str, N ) STRREP_##N( str )
#define STRREP_0(str) ""
#define STRREP_1(str) str
#define STRREP_2(str) str str
#define STRREP_3(str) str str str
...
which works well, but is ugly as I have to define a macro for each repetition length manually. I want to use it together with variadic macros and the macro returning the number of macro arguments shown here.
Since it's a macro and N is a numeric constant anyway, how about this?
#include <stdio.h>
#define REP0(X)
#define REP1(X) X
#define REP2(X) REP1(X) X
#define REP3(X) REP2(X) X
#define REP4(X) REP3(X) X
#define REP5(X) REP4(X) X
#define REP6(X) REP5(X) X
#define REP7(X) REP6(X) X
#define REP8(X) REP7(X) X
#define REP9(X) REP8(X) X
#define REP10(X) REP9(X) X
#define REP(HUNDREDS,TENS,ONES,X) \
REP##HUNDREDS(REP10(REP10(X))) \
REP##TENS(REP10(X)) \
REP##ONES(X)
int main(void)
{
printf(REP(9,0,7, "*")); // "*" repeated 907 times
printf(REP(0,9,2, "#")); // "#" repeated 92 times
printf(REP(0,0,1, "#")); // "#" repeated 1 times
return 0;
}
My suggestion is to use the boost.
E.g.
#include <stdio.h>
#include <boost/preprocessor/repetition/repeat.hpp>
#define Fold(z, n, text) text
#define STRREP(str, n) BOOST_PP_REPEAT(n, Fold, str)
int main(){
printf("%s\n", STRREP("%s ", 3));//STRREP("%s ", 3) -> "%s %s %s "
return 0;
}
I recently discovered a recursion scheme with the CPP c-preprocessor file inclusion mechanism over the __INCLUDE_LEVEL__ preprocessor literal which is treated automatically - so maybe this algorithm only works for gcc ?!?
The algorithm is conceptually unlimited, it can be extended with additional file indirection.
The herin presented code handles an ITERATION_COUNT from 0-39202
With the comment/uncomment of the ITERATION_SEPARATOR you can
generate N elements, or 1 element with N concatenations, suitable for string repetitions.
The ITERATION_ELEMENT macro is used as the "repetition element"
You can compile the code regulary, without any additional defines. The macro invocation inside the code is idempotent.
An exemplary output:
> gcc iterate.c -o iterate -Wall -s -O3 && ./iterate.exe
0-1591 Counter
1592 Elements
iterate.c:
#include <stdio.h>
#include <inttypes.h>
int main(void) {
const char * preproc_array[] = {
#define ITERATION_COUNT 1592 //0-(199*197-1)39202 (maximum counter)
#define ITERATION_SEPARATOR , //this macro, if active, determines wheather there exits N separate elements otherwise, if outcommented, just 1 element with N concatenations
#define ITERATION_ELEMENT 0-__COUNTER__ Counter\n //the expanded macro as an arbitrary element
#include "iterate.h"
};
return !printf("%s%"PRIu32" Elements",preproc_array[
#ifndef NO_ITERATION_SEPARATOR
__COUNTER__-1
#else
0
#endif
], sizeof(preproc_array)/sizeof(const char *));
}
iterate.h:
#define ITERATION_START 1 //start index of first inclusion
#define ITERATION_LIMIT 199 //conforming to CPP preprocessor manual pg. 54 chapter 11.5, a limit of 200 is set arbitrary
#define ITERATION(...) _ITERATION(__VA_ARGS__)
#define _ITERATION(...) #__VA_ARGS__ ITERATION_SEPARATOR
#ifndef ITERATION_SEPARATOR
#define ITERATION_SEPARATOR
#define NO_ITERATION_SEPARATOR
#endif
//here begins the recursive algorithm via preprocessor file inclusion, enable the warnings if you want to see how it loops through
#if __INCLUDE_LEVEL__ <= ITERATION_COUNT/ITERATION_LIMIT
//~ #warning DIV
#define ITERATION_END ITERATION_COUNT/ITERATION_LIMIT+3 // + offset
#include "loop.h"
#define ITERATION_END ITERATION_LIMIT
#include "loop.h"
#include "iterate.h"
#endif
#if __INCLUDE_LEVEL__ == ITERATION_START
//~ #warning MOD
#define ITERATION_END ITERATION_COUNT%ITERATION_LIMIT+ITERATION_START
#include "loop.h"
#if ITERATION_COUNT % ITERATION_LIMIT
#define ITERATION_END 3 // + offset
#include "loop.h"
#endif
#endif
//end of alogrithm
loop.h:
#if __INCLUDE_LEVEL__ < ITERATION_END
#include "loop.h"
ITERATION(ITERATION_ELEMENT)
#undef ITERATION_END
#endif
Not sure whether it can be done with the macro but you can do it with the function like:
char *strrep(const char *str, int nrep)
{
if (nrep <= 0 || !str) return NULL;
char *buf = malloc(strlen(str) * nrep + 1);
if (!buf) return NULL;
for (int i = 0; i < nrep; ++i) {
strcat(buf, str);
}
return buf;
}
Now you can use it:
char *r = strrep("%s", 3);
if (r) {
...
free(r);
}
UPD: If you want to avoid malloc/free this is a variant of the first code:
/* .h */
#define STRREP_MAX_CHARS 1024
#define STRREP_INIT static char __strrep_buffer[STRREP_MAX_CHARS]
#define STRREP(str, nrep) strrep(str, nrep) ? __strrep_buffer : ""
char *strrep(const char *str, int nrep);
/* .c */
STRREP_INIT;
char *strrep(const char *str, int nrep)
{
if (nrep <= 0 || !str) return 0;
if (strlen(str) * nrep >= STRREP_MAX_CHARS) return 0;
memset(__strrep_buffer, 0, STRREP_MAX_CHARS);
for (int i = 0; i < nrep; ++i) {
strcat(__strrep_buffer, str);
}
return __strrep_buffer;
}
Now:
printf("%s\n", STRREP("%s", 3));
OTOH, this looks even uglier than the first one.
How about something like this?
#define DUP2(str) str str
#define DUP4(str) DUP2(str) DUP2(str)
#define DUP8(str) DUP4(str) DUP4(str)
#define DUP16(str) DUP8(str) DUP8(str)
#define DUP32(str) DUP16(str) DUP16(str)
#define DUP64(str) DUP32(str) DUP32(str)
#define DUP128(str) DUP64(str) DUP64(str)
#define DUP256(str) DUP128(str) DUP128(str)
#define DUP512(str) DUP256(str) DUP256(str)
#define DUP1024(str) DUP512(str) DUP512(str)

Resources