printf(" LIST.H ") where LIST.H is a macro - c

#include <stdio.h>
#include<stdlib.h>
#define LIST.H onus;
int main ()
{
char *p,*s;
printf(" LIST.H ");
}
I expect LIST.H to print onus as out put.
But this does not happen.
upon compiling I get a warning
temp.c:3:13: warning: missing whitespace after the macro name
and the output is LIST.H not onus.
How can I get desired thing printed by the above macro?
UPDATE
I want to have the output
as onus with one space before and after the string.

Macros names cannot have . inside them. That's why you get the warning:
warning: missing whitespace after the macro name, after LIST it expects a space, but it gets a . instead.
Also, when a macro name is inside a string(between "string") it is not replaced by the macro definition.
You could do this instead:
#define LISTH "onus"
// and then
printf(LISTH);
which the preprocessor will transform to:
printf("onus");
If you do:
#define LISTH "onus";
the preprocessor will transform it to:
printf("onus";);
which won't compile.

Firstly, you can't use . in macro names.
Secondly, you should "expect" it to print ouns;, since you included a ; into your macro definition.
Thirdly, in order to achieve that you can use "stringization" macro-operator # with some helper macros
#define TO_STRING_(x) #x
#define TO_STRING(x) TO_STRING_(x)
#define LIST_H onus
...
printf(" " TO_STRING(LIST_H) " ");
or, better
printf(" %s ", TO_STRING(LIST_H));

#include <stdio.h>
#define LIST_H "onus"
int main()
{
printf(LIST_H);
}

macros in strings aren't resolved, you need to layers of macro resolution to do that:
#define __STR(x) #x
#define _STR(x) __STR(x)
printf(_STR(LIST));
you also cannot have dots in macro defines last I checked, which would be what your error is about, so rather use LIST_H...

Related

How to pass string as prefix of defined macro

Is there any idea to pass C string as part of the defined macro like below code?
#define AAA_NUM 10
#define BBB_NUM 20
#define PREFIX_NUM(string) string##_NUM
int main()
{
char *name_a = "AAA";
char *name_b = "AAA";
printf("AAA_NUM: %d\n", PREFIX_NUM(name_a));
printf("BBB_NUM: %d\n", PREFIX_NUM(name_b));
return 0;
}
Expected output
AAA_NUM: 10
BBB_NUM: 20
As mentioned in other posts, you can't use run-time variables in the pre-processor. You could however create enum that way. Though it is usually not a good idea to generate identifiers with macros either, save for special cases like when maintaining an existing code base and you are limited in how much of the existing code you can/want to change. So it should be used as a last resort only.
The least bad way to write such macros would be by using a common design pattern called "X macros". These are used when it is important that code repetition should be reduced to a single place in the project. They tend to make the code look rather alien though... Example:
#define PREFIX_LIST(X) \
/* pre val */ \
X(AAA, 10) \
X(BBB, 20) \
X(CCC, 30) \
enum // used to generate constants like AAA_NUM = 10,
{
#define PREFIX_ENUMS(pre, val) pre##_NUM = (val),
PREFIX_LIST(PREFIX_ENUMS)
};
#include <stdio.h>
int main (void)
{
// one way to print
#define prefix_to_val(pre) pre##_NUM
printf("AAA_NUM: %d\n", prefix_to_val(AAA));
printf("BBB_NUM: %d\n", prefix_to_val(BBB));
// another alternative
#define STR(s) #s
#define print_all_prefixes(pre, val) printf("%s: %d\n", STR(pre##_NUM), val);
PREFIX_LIST(print_all_prefixes)
return 0;
}
A macro is only processed before compilation and not at runtime. Your code example does not work as you can see here.
Good practice (for example MISRA coding rules) recommend to use macros as little as possible since it is error prone.
Preprocessor works at compile time and here name_a and name_b are non constant, and even if they were (i.e. const char *str is a real constant in C++ but not in C), there is a literal substitution and the preprocessor does not know the contents of variables.
This works (notice that the parameter should be expanded by another macro in order to get a valid token):
#include <stdio.h>
#define AAA_NUM 10
#define BBB_NUM 20
#define _PREFIX_NUM(string) string##_NUM
#define PREFIX_NUM(string) _PREFIX_NUM(string)
int main(void)
{
#define name_a AAA
#define name_b BBB
printf("AAA_NUM: %d\n", PREFIX_NUM(name_a));
printf("BBB_NUM: %d\n", PREFIX_NUM(name_b));
return 0;
}
There is no way in C to create runtime symbols and use them. C is a compiled language and all symbols have to be known before the compilation.
The preprocessor (which do changes on the text level before the compilation) does not know anything about the C language.

C: Is there a way to define a macro AND output some code in a single statement?

I would like to define a macro that would generate program text for me AND also set some non-string macro value. I know that including #define in another #define is not going to work so I'm trying to find a different way.
A simple example:
#include <stdio.h>
#define START_SYNTHETIC int SYNTHETIC_FUNCTION() {
#define END_SYNTHETIC return 0;}
#define SYNTHETIC_FUNCTION my_function
START_SYNTHETIC
printf("Hello from %s", "SYNTHETIC_FUNCTION");
END_SYNTHETIC
int main() {
my_function();
}
This code kinda works, it produces the following output:
Hello from SYNTHETIC_FUNCTION
There are two problems with it:
function name is not expanded and I just have "SYNTHETIC_FUNCTION" in the output. This is currently not critical but might be needed later on.
I dislike having three lines to start my synthetic function. The empty line inserted by autoformatter is especially irritating. Can I reduce this to just a single macro invocation?
Is there a way to define a macro AND output some code in a single statement?
No, in C macros can't define other macros.
function name is not expanded and I just have "SYNTHETIC_FUNCTION" in the output.
Sure it doesn't - it's inside a string literal. Macro replacement is not done inside a string literal.
Can I reduce this to just a single macro invocation?
I do not understand the point at all of this code. Just use __func__.
int my_function(void) {
printf("Hello from %s\n", __func__);
return 0;
}
or pass the name as a macro parameter:
#define SYNTHETIC(name) \
int name(void) { \
printf("Hello from %s\n", #name); \
printf("but really, just use __func__ anyway...: %s\n", __func__); \
return 0; \
}
SYNTHETIC(my_function)

Why only define a macro if it's not already defined?

All across our C code base, I see every macro defined the following way:
#ifndef BEEPTRIM_PITCH_RATE_DEGPS
#define BEEPTRIM_PITCH_RATE_DEGPS 0.2f
#endif
#ifndef BEEPTRIM_ROLL_RATE_DEGPS
#define BEEPTRIM_ROLL_RATE_DEGPS 0.2f
#endif
#ifndef FORCETRIMRELEASE_HOLD_TIME_MS
#define FORCETRIMRELEASE_HOLD_TIME_MS 1000.0f
#endif
#ifndef TRIMSYSTEM_SHEARPIN_BREAKINGFORCE_LBS
#define TRIMSYSTEM_SHEARPIN_BREAKINGFORCE_LBS 50.0f
#endif
What is the rationale of doing these define checks instead of just defining the macros?
#define BEEPTRIM_PITCH_RATE_DEGPS 0.2f
#define BEEPTRIM_ROLL_RATE_DEGPS 0.2f
#define FORCETRIMRELEASE_HOLD_TIME_MS 1000.0f
#define TRIMSYSTEM_SHEARPIN_BREAKINGFORCE_LBS 50.0f
I can't find this practice explained anywhere on the web.
This allows you to override the macros when you're compiling:
gcc -DMACRONAME=value
The definitions in the header file are used as defaults.
As I said in the comment, imagine this situation:
foo.h
#define FOO 4
defs.h
#ifndef FOO
#define FOO 6
#endif
#ifndef BAR
#define BAR 4
#endif
bar.c
#include "foo.h"
#include "defs.h"
#include <stdio.h>
int main(void)
{
printf("%d%d", FOO, BAR);
return 0;
}
Will print 44.
However, if the conditional ifndef was not there, the result would be compilation warnings of MACRO redefinition and it will print 64.
$ gcc -o bar bar.c
In file included from bar.c:2:0:
defs.h:1:0: warning: "FOO" redefined [enabled by default]
#define FOO 6
^
In file included from bar.c:1:0:
foo.h:1:0: note: this is the location of the previous definition
#define FOO 4
^
I do not know the context but this can be used to give the user the availability to override the values set by those macro definitions. If the user explicitly defines a different value for any of those macros it will be used instead of the values used here.
For instance in g++ you can use the -D flag during compilation to pass a value to a macro.
This is done so that the user of the header file can override the definitions from his/her code or from compiler's -D flag.
Any C project resides on multiple source files. When working on a single source file the checks seem to (and actually) have no point, but when working on a large C project, it's a good practice to check for existing defines before defining a constant. The idea is simple: you need the constant in that specific source file, but it may have been already defined in another.
You could think about a framework/library that gives to the user a default preset that allow the user to compile and work on it.
Those defines are spreaded in different files and the final user is advised to include it's config.h file where he can config its values.
If the user forgot some define the system can continue to work because of the preset.
Using
#ifndef BEEPTRIM_PITCH_RATE_DEGPS
#define BEEPTRIM_PITCH_RATE_DEGPS 0.2f
#endif
allows the user to define the value of the macro using the command line argument (in gcc/clang/VS) -DBEEPTRIM_PITCH_RATE_DEGPS=0.3f.
There is another important reason. It is an error to re-define a preprocessor macro differently. See this answer to another SO question. Without the #ifndef check, the compiler should produce an error if -DBEEPTRIM_PITCH_RATE_DEGPS=0.3f is used as a command line argument in the compiler invocation.

How to define macro function which support no input parameter and support also input parametr in the same time

I want to define a macro function which support at the same time:
1) No input parameter
2) Input parameters
some thing like that:
#define MACRO_TEST(X)\
printf("this is a test\n");\
printf("%d\n",x) // the last printf should not executed if there is no input parameter when calling the macro
In the main:
int main()
{
MACRO_TEST(); // This should display only the first printf in the macro
MACRO_TEST(5); // This should display both printf in the macro
}
You can use sizeof for this purpose.
Consider something like this:
#define MACRO_TEST(X) { \
int args[] = {X}; \
printf("this is a test\n");\
if(sizeof(args) > 0) \
printf("%d\n",*args); \
}
gcc and recent versions of MS compilers support variadic macros - that is macros that work similar to printf.
gcc documentation here:
http://gcc.gnu.org/onlinedocs/gcc/Variadic-Macros.html
Microsoft documentation here:
http://msdn.microsoft.com/en-us/library/ms177415(v=vs.80).aspx
Not exactly that but ...
#include <stdio.h>
#define MTEST_
#define MTEST__(x) printf("%d\n",x)
#define MACRO_TEST(x)\
printf("this is a test\n");\
MTEST_##x
int main(void)
{
MACRO_TEST();
MACRO_TEST(_(5));
return 0;
}
EDIT
And if 0 can be used as skip:
#include <stdio.h>
#define MACRO_TEST(x) \
do { \
printf("this is a test\n"); \
if (x +0) printf("%d\n", x +0); \
} while(0)
int main(void)
{
MACRO_TEST();
MACRO_TEST(5);
return 0;
}
The C99 standard says,
An identifier currently defined as an object-like macro shall not be redefined by another #define reprocessing directive unless the second definition is an object-like macro definition and the two replacement lists are identical. Likewise, an identifier currently defined as a function-like macro shall not be redefined by another #define preprocessing directive unless the second definition is a function-like macro definition that has the same number and spelling of parameters, and the two replacement lists are identical.
I think compiler prompts a warning of redefined MACRO. Hence it is not possible.

Printing name and value of a macro

I have a C program with a lot of optimizations that can be enabled or disabled with #defines. When I run my program, I would like to know what macros have been defined at compile time.
So I am trying to write a macro function to print the actual value of a macro. Something like this:
SHOW_DEFINE(X){\
if( IS_DEFINED(X) )\
printf("%s is defined and as the value %d\n", #X, (int)X);\
else\
printf("%s is not defined\n", #X);\
}
However I don't know how to make it work and I suspect it is not possible, does anyone has an idea of how to do it?
(Note that this must compile even when the macro is not defined!)
As long as you are willing to put up with the fact that SOMESTRING=SOMESTRING indicates that SOMESTRING has not been defined (view it as the token has not been redefined!?!), then the following should do:
#include <stdio.h>
#define STR(x) #x
#define SHOW_DEFINE(x) printf("%s=%s\n", #x, STR(x))
#define CHARLIE -6
#define FRED 1
#define HARRY FRED
#define NORBERT ON_HOLIDAY
#define WALLY
int main()
{
SHOW_DEFINE(BERT);
SHOW_DEFINE(CHARLIE);
SHOW_DEFINE(FRED);
SHOW_DEFINE(HARRY);
SHOW_DEFINE(NORBERT);
SHOW_DEFINE(WALLY);
return 0;
}
The output is:
BERT=BERT
CHARLIE=-6
FRED=1
HARRY=1
NORBERT=ON_HOLIDAY
WALLY=
Writing a MACRO that expands to another MACRO would require the preprocessor to run twice on it.
That is not done.
You could write a simple file,
// File check-defines.c
int printCompileTimeDefines()
{
#ifdef DEF1
printf ("defined : DEF1\n");
#else // DEF1
printf ("undefined: DEF1\n");
#endif // DEF1
// and so on...
}
Use the same Compile Time define lines on this file as with the other files.
Call the function sometime at the start.
If you have the #DEFINE lines inside a source file rather than the Makefile,
Move them to another Header file and include that header across all source files,
including this check-defines.c.
Hopefully, you have the same set of defines allowed across all your source files.
Otherwise, it would be prudent to recheck the strategy of your defines.
To automate generation of this function,
you could use the M4 macro language (or even an AWK script actually).
M4 becomes your pre-pre-processor.
#ifdef MYMACRO
printf("MYMACRO defined: %d\r\n", MYMACRO);
#endif
I don't think what you are trying to do is possible. You are asking for info at runtime which has been processed before compilation. The string "MYMACRO" means nothing after CPP has expanded it to its value inside your program.
You did not specify the compiler you were using. If this is gcc, gcc -E may help you, as it stops after the preprocessing stage, and prints the preprocessing result. If you diff a gcc -E result with the original file, you may get part of what you want.
Why not simply testing it with the preprocessor ?
#if defined(X)
printf("%s is defined and as the value %d\n", #X, (int)X);
#else
printf("%s is not defined\n", #X);
#endif
One can also embed this in another test not to print it everytime:
#if define(SHOW_DEFINE)
#if defined(X)
printf("%s is defined and as the value %d\n", #X, (int)X);
#else
printf("%s is not defined\n", #X);
#endif
#endif
Wave library from boost can be helpful also to do what you want. If your project is big enough, I think it is worth trying. It is a C++ preprocessor, but they are the same any way :)
I believe what you are trying to do is not possible. If you are able to change the way your #defines work, then I suggest something like this:
#define ON 1
#define OFF 2
#define OPTIMIZE_FOO ON
#define OPTIMIZE_BAR OFF
#define SHOW_DEFINE(val)\
if(val == ON) printf(#val" is ON\n");\
else printf(#val" is OFF\n");
It is not possible indeed, the problem being the "not defined" part. If you'd relied on the macro values to activate/deactivate parts of your code, then you could simply do:
#define SHOW_DEFINE(X) \
do { \
if (X > 0) \
printf("%s %d\n", #X, (int)X); \
else \
printf("%s not defined\n", #X); \
} while(0)
Based on Chrisharris, answer I did this.
Though my answer is not very nice it is quite what I wanted.
#define STR(x) #x
#define SHOW_DEFINE(x) printf("%s %s\n", #x, strcmp(STR(x),#x)!=0?"is defined":"is NOT defined")
Only bug I found is the define must not be #define XXX XXX (with XXX equals to XXX).
This question is very close from Macro which prints an expression and evaluates it (with __STRING). Chrisharris' answer is very close from the answer to the previous question.
you can use an integer variable initialized to 1.
multiply the #define with this variable and print the value of variable.

Resources