Restoring definitions and macros - c

Is there a way to restore macros in C, so that you can define a new macro, under which name probably other macros are already defined, and redefine it with the previous value?
so that when new defined macros are deleted and eventually redefined macros are resetted to its previous state?
Example:
// a macro parameter used in a library
#define size 10
#include <library/use_size.h>
//here the command/pragma to save the definitions
#define size (100 / sizeof(size_t))
// some use of size ...
//here the command/pragma to reset the definitions
#include <library/allocator_with_size.h>
#undef size
// use size as a variable name
size_t size = 0;
//...
size += 123;
Edit: I do not want to use #undef, because it does not restore old macros. Also, if you have many macros, eg for using them in a X-macro-list (in a long repetitive code/declaration of constant arrays and structs), it looks ugly, if there are many #undef directives.

Ok I researched myself and found the pragmas push_macro and pop_macro, supported by clang, gcc and visual c++. I use clang, so it is no problem to use it. The disadvantage: it does not reduce the line-count if you want to restore multiple macros ¹, but it restores the macros and can be encapsulated:
#pragma push_macro("size")
#define size (100 / sizeof(size_t))
#pragma pop_macro("size")
Notes:
¹ I defined multiple macros and tried to restore them with:
#pragma push_macro("size", "key", "name")
// define them all
#pragma pop_macro("size", "key", "name")
But that is not implemented into the compilers yet. So for each macro there must be a seperate line to do this.

Related

Use a macro both in implementation and header and then undefine it

I have a macro that should be used both in my source file and header one. However I don't wan't other code linked to the final object to access that macro (more than anything else I don't want the macro to go causing unexpected errors in other files). I thought about using a macro with a long and complicated name that will be unlikely used from other code, however this solution kinda looks ugly to me. Obviously the most simple solution would be to undefine the macro in some way, however if I define the macro in the header and then undefine it – I think – I won't be able to access it anymore from the source file. What should I do?
// hi.h
#define string char *
void greet(string x);
// hi.c
#include "hi.h"
void greet(string x) {
printf("Hi!");
}
Okay, don't kill me, this was just an example, i know #define string char * is horrible.
Last minute thought: Maybe I can underfine the macro at the end of the source file, is this acceptable to do?
I guess you could conditionally "undefine" macro at the end of the header when the a magic macro is not defined. The blessed source file would have to define this macro prior to including a header.
// header.h
...
#ifndef MAGIC_MACRO
#undef string
#endif
// common source
#include "header.h"
// blessed source
#define MAGIC_MACRO
#include "header.h"
This solution will work great as long as no macro defined inside the header uses string macro.
What should I do?
Pick option 1 a macro with a long and complicated name that will be unlikely used from other code as it's the simplest and most obvious. Do not use a complicated name - just use a name so that you and other developers will know it's a private symbol, that's all.
// hi.h
// this macro is private
#define _lib_string char *
Remember about reserved words. Example: https://github.com/GNOME/glib/blob/main/glib/glib-private.h#L32 .
he most simple solution would be to undefine the macro in some way, however if I define the macro in the header and then undefine it – I think – I won't be able to access it anymore from the source file
If you go this way, you'll end up with spaghetti code, where some global state affects what you have. For example:
// hi.h
#define string char *
void greet(string x);
#ifndef FROM_HI_C
#undef string
#endif
// hi.c
#define FROM_HI_C
#include "hi.h"
void greet(string x) {
printf("Hi!");
}
Maybe I can underfine the macro at the end of the source file, is this acceptable to do?
Other files see only the header file - they are unaffected by anything in the source file.

Any workaround to self-referential macros in C? I'd like to append to a macro

I have a file that uses a FLAGS macro from an include that I do not control. What is in FLAGS is not consistent. Occasionally I need to change FLAGS to add a flag to it. Now I know I can't do #define FLAGS FLAGS|MY_FLAG, but I thought if I stored FLAGS in a temporary variable that I could then undefine it and redefine it using the temporary and my flag. For example:
// Assume this next line is what's in the include file
#define FLAGS (1|2|4)
// The rest of this is source, assume compile with -DMOD
#ifdef MOD
#define TEMP (FLAGS|8)
#undef FLAGS
#define FLAGS TEMP
#endif
int main()
{
printf("0x%x\n", FLAGS);
}
And if MOD is defined the error is error: 'FLAGS' was not declared in this scope. I know that I can change all the actual C code that uses FLAGS to instead use FLAGS|MY_FLAG but I was hoping to modify the macro rather than all the code.
Your only real way to do exactly what you are trying to do is to define an additional macro
// Assume this next line is what's in the include file
#define FLAGS_FOR_A (1|2|4)
#define FLAGS FLAGS_FOR_A
// The rest of this is source, assume compile with -DMOD
#ifdef MOD
#undef FLAGS
#define FLAGS ( FLAGS_FOR_A | 8 )
#endif
int main()
{
printf("0x%x\n", FLAGS);
}
Macros just do simple text replacement, computed before runtime
You can do something logically equivalent to #define FLAGS FLAGS|MY_FLAG if you define the macro as modifiable using Boost's "evaluated slots":
#include <boost/preprocessor/slot/slot.hpp>
// define FLAGS as a modifiable macro and create a setter for it
#define FLAGS BOOST_PP_SLOT(1)
#define UPDATE_FLAGS BOOST_PP_ASSIGN_SLOT(1)
int main(void) {
// set the initial value of FLAGS
#define BOOST_PP_VALUE (1|2|4)
#include UPDATE_FLAGS
printf("0x%x\n", FLAGS); // 0x7
// update FLAGS with a new value using the old one
#define BOOST_PP_VALUE (FLAGS|8)
#include UPDATE_FLAGS
printf("0x%x\n", FLAGS); // 0xf
}
Despite being witchcraft, this is completely standard-compliant C, no extensions. Only works for integers.
(It works by taking advantage of something important: macros aren't just expanded into program code, but also need to be expanded to determine whether to follow an #if branch as well. Since #if directives are also capable of evaluating integer math, this is able to expand the actual numeric value and use it to construct a new expansion for the PP_SLOT that doesn't involve a reference to any macro name. This is all hidden behind the #include UPDATE_FLAGS directives.)

Call from c code a kernel variable in freebsd

I found some online resources about this topic but still can not understand how it works.
Lets assume that I have a global variable with following specification
in file: /sys/sys/sysctl.h
#define USER_TZNAME_MAX 20 /*test var*/
and in file /usr/src/sys/kern/kern_mib.c a
SYSCTL_INT(_user, USER_TZNAME_MAX, tzname_max, CTLFLAG_RW, 0, 0, "something");
can anyone show practically how to change the variable value and set another value in a c source file?
Thank you
#define USER_TZNAME_MAX is not defining a global variable, it is a preprocessor macro.
Before the compiler compiles the code the preprocessor is run to expand macros and include/exclude code as defined by definitions.
In an example such as this, the preprocessor will replace all instances of the string "USER_TZNAME_MAX" in the source with the string "20":
// this
int i = USER_TZNAME_MAX;
// will be expanded to this:
int i = 20;
Therefore you can't change this variable at run time because a) it isn't a variable, and b) it's a constant.
If you're talking about changing the value used in your own code you can do this:
#ifdef USER_TZNAME_MAX
#undef USER_TZNAME_MAX
#endif
#define USER_TZNAME_MAX (32)
In programs, you should use sysctl(3) to get or set system information.

#define an object with no value

I am now read some c code. And is not very clear about the "#define someting" expression.
For example, I saw this code:
typedef enum cairo_path_op {
CAIRO_PATH_OP_MOVE_TO = 0,
CAIRO_PATH_OP_LINE_TO = 1,
CAIRO_PATH_OP_CURVE_TO = 2,
CAIRO_PATH_OP_CLOSE_PATH = 3
} __attribute__ ((packed)) cairo_path_op_t; /* Don't want 32 bits if we can avoid it. */
#ifndef __GNUC__
#define __attribute__(x)
#endif
I take attention to the "__attribute__(x)". since in other header file , the "__attribute__(x)" is defined with no value, but how it take effect in the enum "cairo_path_op" define?
This is for portability reasons.
__attribute__() is a GCC extension for modifying various properties and behavior of functions, variables, types, etc.
If a non-GCC-compatible compiler tries to compile code that uses this extension, it won't able to do so and will throw a syntax error.
In order to avoid this, the author of the code makes the preprocessor replace this keyword with nothing if __GNUC__ is not defined (i. e. if the compiler is not a GCC-compatible one), so that the code builds on a bigger variety of platforms.

Temporarily overwrite a macro in C preprocessor

I need to temporarily overwrite a macro and then restore it. Like:
#define FOO X
#save FOO
#define FOO Y
...
#restore FOO
Is it possible in standard C preprocessor? In GCC?
ADDED. About real world example. I use a global macro for error exception. It acts like assert, but for persistent usage, not only for debug versions; so, for example, I usually call functions (with side-effect) inside the macro. It's defined once, but the definition isn't persistent; therefore I don't know it a-priori. For some piece of code I need its own, modified version of the macro, but I want to save general style of code. It's looks ugly when one part of code uses the one macro, other part uses other macro -- both macros have the same purpose, but slightly different implementation.
So, it's good for me to save original macro temporarily, use different version for a part of code, after that restore original macro.
This is possible with #pragma push_macro and #pragma pop_macro. These are not standard C—they're originally an MSVC extension—but clang supports them, and so does GCC.
Example usage:
int main() {
#define SOME_MACRO 1
printf("SOME_MACRO = %d\n", SOME_MACRO);
#pragma push_macro("SOME_MACRO")
#define SOME_MACRO 2
printf("SOME_MACRO = %d\n", SOME_MACRO);
#pragma pop_macro("SOME_MACRO")
printf("SOME_MACRO = %d\n", SOME_MACRO);
return 0;
}
prints:
SOME_MACRO = 1
SOME_MACRO = 2
SOME_MACRO = 1
You can also #undef a macro inside a push_macro / pop_macro pair, and the pop_macro call will redefine it.
As already said, it is not really possible. Depending on the situation, this might be a workaround:
#include "generalmacrodefs.h" // put them in here or include them indirectly
#undef macro1
#define macro1 "specialized temporary value"
#undef macro1
#include "generalmacrodefs.h" // restores
This requires that generalmacrodefs.h uses a pattern like this at least for the definitions you might temporarily overwrite:
#ifndef macro1
#define macro1 "original value"
#endif
The closest you can come in C is the #undef directive, which simply undefines the macro, allowing it to be replaced:
#define FOO X
...
#undef FOO
#define FOO Y
...
#undef FOO
#define FOO X
The problem is that you cannot know the 'old' value of FOO once you redefine it - so your values must be hard-coded in one place.
You cannot create a macro to save the values for you either, as it isn't possible to have a macro that creates other preprocessor directives in standard C.

Resources