Macro questions - c

On a software project (some old C compiler) we have a lot of variables which have to be saved normal and inverted.
Has somebody a idea how i can make a macro like that?
SET(SomeVariable, 137);
which will execute
SomeVariable = 137;
SomeVariable_inverse = ~137;
Edit:
The best Solution seems to be:
#define SET(var,value) do { var = (value); var##_inverse = ~(value); } while(0)
Thanks for the answers

Try this
#define SET(var,value) do { var = (value); var##_inverse = ~(value); } while(0)
EDIT
Couple of links to the reason behind adding a do/while into the macro
https://stackoverflow.com/questions/257418/do-while-0-what-is-it-good-for
http://www.rtems.com/ml/rtems-users/2001/august/msg00111.html
http://c2.com/cgi/wiki?TrivialDoWhileLoop
http://blogs.msdn.com/jaredpar/archive/2008/05/21/do-while-0-what.aspx

One hazard I haven't seen mentioned is that the 'value' macro argument is evaluated twice in most of the solutions. That can cause problems if someone tries something like this:
int x = 10;
SET(myVariable, x++);
After this call, myVariable would be 10 and myVariable_inverse would be ~11. Oops. A minor change to JaredPar's solution solves this:
#define SET(var,value) do { var = (value); var##_inverse = ~(var); } while(0)

Why are you storing the inverse when it can be so easily calculated? This seems like a bad idea to me.

You can do it in a single statement, which avoids having to use do {} while (0).
#define SetInverse(token, value) (token##_inverse = ~(token = (value)))
Also, this only evalutes (value) once, which is always nice.

#define SetInverse(token, value) { token = value; token##_inverse = ~value; }
Jinx, Jared - like the while (0) in yours

Just to offer an alternative method:
Store each variable as a structure like this:
typedef struct
{
u32 u32Normal;
u32 u32Inverted;
} SafeU32TYPE
Then have a function which takes a pointer to one of these, along with the value to be set, and stores that value with its inverse:
void Set(SafeU32TYPE *pSafeU32, u32Data)
{
if(pSafeU32 != NULL)
{
pSafeU32->u32Normal = u32Data;
pSageU32->u32Inverted = ~u32Data;
} /* if */
} /* Set() */
Advantage: if you need the set function to do something more powerful, such as boundary checking, or storing in some more complex way, then it can be easily extended.
Disadvantage: you'll need a different function for each type used, and if processor resource is an issue, this is less efficient than using a macro.

Related

Pointer decryption function not working as intended

First of all, it is important to say that the code will be a mess, I know that and there is a reason behind the messy code, but I prefer not to specify why to avoid going off track.
This snippet of code decrypts a pointer:
//LLUNGO is long long
//PLLUNGO is long long pointer
//SCANVELOCE is __fastcall
LLUNGO SCANVELOCE DecryptPointer(PPTR_SECRET _pSecret, PLLUNGO _OldPointer)
{
_OldPointer = (PLLUNGO) PTR_ENCRYPTION_ALGORITHM(*_OldPointer, _pSecret->Segreto);
INTERO Reference = GetReferenceToPtr(_pSecret, _OldPointer);
if (PTR_BAD_REFERENCE(Reference))
QUICK_PRINT("Bad reference error.\n");
return PTR_ENCRYPTION_ALGORITHM((LLUNGO)_pSecret->Riferimenti[Reference], _pSecret->Segreto);
}
using the following macros:
#define PTR_ENCRYPTION_ALGORITHM(PTR, KEY) (~(PTR ^ KEY))
#define PTR_BAD_REFERENCE(PTR) ((-1) == (PTR))
Now the problem is when I use the macro stated below, for some reason even if I am using the right arguments it is still throwing me this error:
no instance of overloaded function "DecryptPointer" corresponds to the
arguments.
Consider that NBYTE is BYTE and REGISTRA is the register keyword.
NBYTE SCANVELOCE MFINIT(LLUNGO _FuncAddr, PMUTILATE_FUNCTION _Function)
{
if (!_FuncAddr || !_Function)
return FALSO;
SELF_PTR_DECRYPTION( _FuncAddr ); //error thrown here
SELF_PTR_DECRYPTION( _Function ); //and here too!
for (REGISTRA PNBYTE Current = (PNBYTE)_FuncAddr; ; Current--)
{
if (MF_PUSH_EBP == *Current)
{
_Function->Inizio = (LLUNGO)Current;
break;
}
}
And the SELF_PTR_DECRYPTION macro + everything else necessary for the DecryptPointer function to work:
(PTR_SECRET being a struct)
#define SELF_PTR_DECRYPTION(X) ((X) = (PTR_DECRYPTION(X)))
#define PTR_DECRYPTION(X) DecryptPointer(&PTR_SECRET_NAME, X)
#define PTR_SECRET_NAME g_PTR_SECRET
INIT(PTR_SECRET PTR_SECRET_NAME);
Again sorry for the stupidly messy code, I'm struggling too, just like everyone reading this probably will, but again there is a reason behind the mess.
The solution has been found in the comments by #yano:
you've taken me straight to macro hell. If I'm following correctly,
_FuncAddr in the SELF_PTR_DECRYPTION( _FuncAddr ); call ends up being the 2nd argument to DecryptPointer, which expects a PLLUNGO type.
However, _FuncAddr is a LLUNGO type. And if its complaining about "no
overloaded function" it sounds like you're using a C++ compiler, not
C.
Many thanks, and sorry for the absolute mess of code I presented here.

Can I turn this requirement into a macro?

I have C programs with decrementing software counters. If for instance I want to blink an led every 2 seconds I can do:
if(!ledT) {
ledT = 200;
// code
// code
// code
}
Because I always do the exact same combination with every counter, I tend to type it one line.
if(!ledT) { ledT = 200;
// code
// code
// code
}
For the entire if-line I'd like to use a macro instead. So the code would look something like:
expired(ledT, 200) {
// code
// code
// code
}
I use something similar in my state machine code for the entry state.
if(runOnce) { runOnce = false;
// code
// code
// code
Desired syntax:
entryState {
// code
// code
// code
.
#define entryState if(runOnce) { runOnce = false; // this ofcourse cannot work But something like this is what I want.
I've made several attempts but I got nowhere. The problem is that the { is somewhere in the middle of the macro and I want to type a { behind the macro because as we all know, no code editor can live with an unequal number of { and }.
expired(ledT, 200); // expired is macro, not function
// code
// code
// code
}
So this is out of the question.
Whilst reading about macros, I've read something interesting about using: do ... while(0). This 'trick' abuses the compiler's optimization feature to create a certain macro, which would otherwise be impossible.
This site
sheds some light about this manner.
Is there a way to use some kind of 'macro trick' to achieve what I want?
So again, that is transforming:
// this
if(runOnce) {
runOnce = false;
// code
// code
// code
// into this
entryState {
// code
// code
// code
// and this:
if(!someTimer) {
someTimer = someInterval;
// code
// code
// code
// must be transformed into:
timeExpired(someTimer, someInterval) {
// code
// code
// code
And an answer like "No, it simply cannot be done" will also be accepted (providing you know what you are talking about)
EDIT:
I need to add an addition because not everybody seems to know what I want, the last given answer is not even aimed at the specific problem at hand. Somehow toggling IO suddenly became important? Therfor I altered my code examples to better illustrate what the problem is.
EDIT2:
I agree that the the timeExpired macro does not improve readability at all
To show that some macros can improve readabilty I'll give a snippet of a state and a state machine. This is how a generated state looks like in my code:
State(stateName) {
entryState {
// one time only stuff
}
onState {
// continous stuff
exitFlag = true; // setting this, exits the state
}
exitState {
// one time only stuff upon exit
return true;
}
}
Currently in place with these macros:
#define State(x) static bool x##F(void)
#define entryState if(runOnce)
#define onState runOnce = false;
#define exitState if(!exitFlag) return false; else
I think I should I should exchange return true; in the states by EXIT or something prittier.
And the state machine which calls these States looks like:
#undef State
#define State(x) break; case x: if(x##F())
extern bit weatherStates(void) {
if(enabled) switch(state){
default: case weatherStatesIDLE: return true;
State(morning) {
if(random(0,1)) nextState(afternoon, 0);
else nextState(rain, 0); }
State(afternoon) {
nextState(evening, 0); }
State(evening) {
if(random(0,1)) nextState(night, 0);
else nextState(thunder, 0); }
State(night) {
nextState(morning, 0); }
State(rain) {
nextState(evening, 0); }
State(thunder) {
nextState(morning, 0); }
break; }
else if(!weatherStatesT) enabled = true;
return false; }
#undef State
The only thing which is not generated are the 'if' and 'else' before the 'nextState()' functions. These 'flow conditions' need filling in.
If a user is provided with a small example or an explanation, he should have no difficulty at all with filling in the states. He should also be able to add states manually.
I'd even like to exchange this by macros:
extern bit weatherStates(void) {
if(enabled) switch(state){
default: case weatherStatesIDLE: return true;
and
break;} }
else if(!weatherStatesT) enabled = true;
return false;}
Why would I do this? To hide irrelevant information out of your display. To remove alot of tabs in the state machine. To increase overal readability by using a simple syntax. Like with 3rd library functions you need to know how to use the code rather to know how the function does the trick.
You don't need to know, how a state signals that it is ready. It is more important to know that the function in question is used as a state function than to know that it returns a bit variable.
Also I test macros before using. So I don't provide somebody with state machines that may show strange behavior.
There’s no need to employ macros here, and doing so leads to highly un-idiomatic C code that doesn’t really have any advantages over proper C code.
Use a function instead:
int toggle_if_unset(int time, int pin, int interval) {
if (time == 0) {
time = 200;
TOG(pin);
}
return time;
}
ledT = toggle_if_unset(ledT, ledPin, 200);
(I’m guessing appropriate parameter names based on your example; adjust as appropriate.)
What’s more, it looks as if ledT and ledPin are always paired and belong together, in which case you should consider putting them into a struct:
struct led {
pin_t pin;
int interval;
};
void toggle_if_unset(struct led *led, int new_interval);
Or something along these lines.
Given that this is for some old 8051 legacy project, it is extremely unlikely that you need to create abstraction layer macros for pin I/O handling. You'll only have just so many pins. Your original code is most likely the best and clearest one.
If you for some reason worry about code repetition, because you have multiple combinations of the product/support multiple PCB with different routing etc, and you are stuck with your current code base... then as a last resort you could use macros to avoid code repetition. This also assuming that you are a seasoned C programmer - otherwise stop reading here.
What you will be looking at in that rare scenario is probably something that's known as "X macros", which is about declaring a whole list of pre-processor constants. Then whenever you need to do something repetitive, you call upon that list and use the constants inside it that you are interested for that specific call. Each call is done by specifying what the macro "X" should do in that particular call, then undefined the macro afterwards.
For example if you have ports A, B, C, you have LEDs on port A:0, B:1 and C:2 respectively and wish to use different delays per pin, you can declare a list like this:
#define LED_LIST \
/* port pin delay */ \
X(A, 0, 100) \
X(B, 1, 200) \
X(C, 2, 300) \
Then you can call upon this list when you need to do repetitive tasks. For example if these ports have data direction registers you need to set accordingly and those registers are called DDRA, DDRB, DDRC (using Motorola/AVR naming as example):
/* set data direction registers */
#define X(port, pin, delay) DDR##port |= 1u<<pin;
LED_LIST
#undef X
This will expand to:
DDRA |= 1u<<0;
DDRB |= 1u<<1;
DDRC |= 1u<<2;
Similarly, you can initialize the counters as:
/* declare counters */
#define X(port, delay) static uint16_t count##port = delay;
LED_LIST
#undef X
...
/* check if counters elapsed */
#define X(port, delay) if(count##port == 0) { count##port = delay; PORT##port ^= 1u << pin; }
LED_LIST
#undef X
(I replaced the toggle macro with a simple bitwise XOR)
Which will expand to:
static uint16_t countA = 100;
static uint16_t countB = 200;
static uint16_t countC = 300;
...
if(countA == 0)
{
countA = 100;
PORTA ^= 1u << 0;
}
if(countB == 0)
{
countB = 200;
PORTB ^= 1u << 1;
}
if(countC == 0)
{
countC = 300;
PORTC ^= 1u << 2;
}
And of course avoid using 16 bit counters like done here unless you must, since you are working with a crappy 8-bitter.
#define LL(ledT) do {if(!ledT) { ledT = 200; TOG(ledPin); }}while(0)
Whilst reading about macros, I've read something interesting about
using: do ... while(0). This 'trick' abuses the compiler's
optimization feature to create a certain macro, which would otherwise
be impossible.
Most of the opinions there are actually wrong. There is nothing about optimizations.
The main reason is to make macros using curled braces to compile at all.
This one will not compile
#define A(x) {foo(x);bar(x);}
void foo1(int x)
{
if (x) A(1);
else B(0);
}
but this one will compile
#define A(x) do{foo(x);bar(x);}while(0)
void foo1(int x)
{
if (x) A(1);
else B(0);
}
https://godbolt.org/z/4jH2jP
DISCLAIMER: I don't recommend using this solution.
I had a go at trying to make this into macro's. It is indeed possible but if it's faster, that's another question. As you make a new variable each time you call the macro.
#include <stdio.h>
#define entryState(runOnce) int temp_state = runOnce; if (runOnce) runOnce = 0; if (temp_state)
#define timeExpired(someTimer, someInterval) int temp_expired = someTimer; if (!someTimer) someTimer = someInterval; if (!temp_expired)
int main(int argc, const char* argv[]) {
int runOnce = 1;
int someTimer = 0;
int someInterval = 200;
timeExpired(someTimer, someInterval) {
printf("someTimer is Expired\n");
}
printf("someTimer: %i\n\n", someTimer);
entryState(runOnce) {
printf("this is running once\n");
}
printf("runOnce: %i\n", runOnce);
}
Compiling and running:
c:/repo $ gcc test.c -o test
c:/repo $ ./test.exe
someTimer is Expired
someTimer: 200
this is running once
runOnce: 0
I don't have a C51 compiler at hand now, so I let the testing on the 8051 over to you.

Array of macros in c -- is it possible

I was wondering if it is possible to create something like an array of macros.
I've implemented the following code which works:
struct led_cmds_
{
ioport_pin_t *commands[LED_COUNT] ;
};
struct led_cmds_ the_led_cmd_ ;
void populate() {
the_led_cmd_.commands[0] = SPECIFICPIN(0);
}
and in main:
int main(void)
{
//.....
populate();
LED_On(the_led_cmd_.commands[0]);
}
SPECIFICPIN(x) is macro defined as:
#define SPECIFICPIN(X) (LED##X##_PIN)
What I was hoping for is a way to is a way to do something like this:
#define ioport_pin_t* ARR_LED[LED_COUNT] \
for (int j = 0; j < LED_COUNT; j++) ARR_LED[j] = SPECIFICPIN(j);
and then only need to call the following when I want to use the specific pin
LED_On(ARR_LED[some_number])
when I try to do that I get an ARR_LED undeclared (first use in this function) error.
When I try to call SPECIFICPIN(x) where x is an int iterator in a for loop for example, I get an error saying something like 'LEDx_PIN' undeclared...
You need to work on your terminology. An array of macros is not possible. Macros are no data type, but rather pure text replacement before your program is actually compiled.
I guess " populate an array using macros " is what you want to do. But it is not possible to do that in a compile-time loop - What you seem to want to achieve with your ioport_pin_t macro attempt. Macros do not have the capability to expand to more instances of text elements than you have initially given. There is no such feature as looping at compile time through macro expansions and do repetitive expansion of macros.
Your for loop loops at run-time, while the macro is being expanded at compile-time. Once you have made yourself aware what is done by the preprocessor what is done by the compiler, and what is done at run-time by the finished program, you will see that will not work.
Something like
#define P(X) {(LED##X##_PIN)}
ioport_pin_t *commands[LED_COUNT] = {
P(0), P(1), P(2),......}
#undefine P
Would be the closest thing possible to what you seem to want. Note the main use of the pre-processor is not to save you typing effort - You would be better off using copy & paste in your editor, achieve the same thing and have clearer code.
An array as tofro's answer is the way to go. However in cases that couldn't be solved simply with an array then there's another way with switch
#define SPECIFICPIN(X) (LED##X##_PIN)
void setpin(int pin, int value)
{
switch (pin)
{
case 1:
SPECIFICPIN(1) = value;
doSomething(); // if needed
break;
case x: ...
default: ...
}
}

goto label trick in a macro for condition

There was one evil macro trick I DON'T REMEMBER and it was a lot like this:
public :
var = 3;
}
Which should expand to
if(route == ROOTING_PUBLIC)
{
var = 3;
}
How can I achieve something like this ?
Macros are used to reduce clutter; though a lot of clutter indicates problems with the program structure.
The OP's notion of the possible macro does not match C-syntax. But something along those lines might be:
#define if_ROOTED(name) if (ROOTED_##name & input) { output = e##name; }
#define ROOTED_FIRST 16
#define ROOTED_SECOND 64
#define eFIRST 1
#define eSECOND 2
if_ROOTED(FIRST);
if_ROOTED(SECOND);
where input and output and the repetitive test are the "clutter" to be eliminated. Making a table would be a better way to reduce clutter; however OP asked for a hint about macros.
Now that I found the implementation of such bad idea, I also could understand the deeper sense in it.
The code
#define public if(route == ROOTING_PUBLIC) { public_offset
The usage
public :
var = 3;
} // <-- makes no sense
The idea
To avoid loops, to reduce the spaghetti code and to demonstrate more exotic code. It will be better to be implemented with an id system as such:
#define public(id) if(route == ROOTING_PUBLIC) { public_##id
And then if the user decides to loop the code (that by semantics will be invoked solely "publicly"):
public(2) :
var = 3;
if(var > 3) goto public_2; // or #define repeat(x, id) goto x##_##id
}
Even better version of it will include the omitting of magic numbers, replacing it with user_id

unix DECLARE_WAIT_QUEUE_HEAD (var) var prototype?

i want to work with 2 queue in the module where i change my pointer to them
therefore i need to use :
//declartion
wait_queue_head_t **currentQ;
DECLARE_WAIT_QUEUE_HEAD (readWaitQ1);
DECLARE_WAIT_QUEUE_HEAD (readWaitQ2);
if(condition){
currentQ = &readWaitQ1;
}else{
currentQ = &readWaitQ2;
}
but i get incorrect type for wake_up an other stuff using the queue.
even thought i google it i couldnt find an answer can someone just give me the prototype needed?...
Since the macro is (see here):
#define DECLARE_WAIT_QUEUE_HEAD(name) \
wait_queue_head_t name = __WAIT_QUEUE_HEAD_INITIALIZER(name)
that means that:
DECLARE_WAIT_QUEUE_HEAD (readWaitQ1);
translates to:
wait_queue_head_t readWaitQ1 = ...;
Now with your current code:
wait_queue_head_t **currentQ;
currentQ = &readWaitQ1;
you have one too many indirections on currentQ. You should try:
wait_queue_head_t *currentQ;
instead.

Resources