In C macros, where does the function named defined() come from? - c

In the code below, I don't understand the defined() function used inside #if; where is it defined?
Can anyone point me to a good resource in C language, where I could go deeper in these kinds of kinds of stuff?
#include <stdio.h>
#define Macro 7
void initMSP(void){
printf("OKay with MSP platform\n");
}
void initKine(void){
printf("Done with Kine\n");
}
//#define KINETICS
#define MSP
int main(){
printf("Hello world program\n");
printf("%d\n",Macro);
#if defined(KINETICS) && !defined(MSP)
initKine();
#elif defined(MSP) && !defined(KINETICS)
initMSP();
#else
#error "Please define a Platform "
#endif
}

defined is not a function. It is a syntactic construct of the C preprocessor, just like #define, #ifdef, and so forth. The C language proper (to the extent that you can divorce C from its preprocessor) never directly interacts with defined. It exists during preprocessing and that's that.

Related

conflicting declaration of C function With #ifdef __cplusplus

I failed to define overloading functions with error message of error: conflicting declaration of C function if enclosing by #ifdef __cplusplus blocks.
Below is a simple code for an easy view. This piece of code worked fine without #ifdef __cplusplus blocks.
However, my project code does need #ifdef __cplusplus as it involves combination of C and C++ codes.
Command lines after #ifdef __cplusplus block should be C++, why did it fail to define the overloading function? How to fix this problem with presence of #ifdef __cplusplus blocks?
#include <iostream>
using namespace std;
#ifdef __cplusplus
extern "C"
{
#endif
int add(int x)
{
return x;
}
int add(int x, int y)
{
return x + y;
}
int main() {
// cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
int X = add(2);
int Z = add(8,2);
cout <<X<<" "<<Z<<endl;
return 0;
}
#ifdef __cplusplus
}
#endif
Command lines after #ifdef __cplusplus block should be C++
First of all, I believe you have a misconception of #ifdef __cplusplus, this macro only checks if your compiler is a C++ compiler or not.
You rather need focus on extern "C" {}. This block of code explicitly tells your compiler, that codes inside this block must be in C language(not C++).
This is important since C and C++ have different mechanisms of storing and calling functions from binary. (Called name mangling). Better to say, C and C++ binaries are not compatible. So extern "C" will tell your compiler that your functions C codes, and those function names are not mangled.
So #ifdef __cplusplus checks if your code is C or C++; if your code is in C++, insert extern "C" { that tells your compiler that those codes in this block are C code.
And since function overloading is not a part of C language, your compiler will cause an error inside that block. (This matters with name mangling).
But this macro is mostly used in header files, not source files. Because the purpose of this macro is to enable your code to be included in both C and C++ code, but source files cannot be and must not be included by another source.

What does the c precompiler do with macros defined as (void)0

I have some macros that are defined based on compiler flags. I'm trying to decide whether I would rather have the macro defined as (void)0 or have it undefined and cause a compile time error.
i.e.
#ifdef DEBUG
#define PRINTF(...) printf(__VA_ARGS__)
#else
#define PRINTF(...) (void)0
#endif
int main(void) {
...
PRINTF("something");
...
}
vs.
#ifdef DEBUG
#define PRINTF(...) printf(__VA_ARGS__)
#endif
int main(void) {
...
#ifdef DEBUG
PRINTF("something");
#endif
...
}
I'm not sure which technique I prefer. On one hand wrapping every PRINTF statement with #ifdef's would be ugly. On the other hand it would be nice to know at compile time if I've called a function that doesn't really work in the context.
I think the deciding factor will be whether or not having the (void)0 macros is going to affect the size of the executable.
When the code is compiled, what happens to the (void)0's? If PRINTF is defined as (void)0, does that mean the executable is going to contain some sort of (void)0 instruction or will it be completely ignored?
(void) 0;
is an expression statement with no side-effect. Any sane implementation will optimize this statement out (what else an implementation could do with such a statement?).
Having (void) 0 as a macro definition is endorsed by the C Standard as it appears in (C11) 7.2p1 for assert macro definition if NDEBUG is defined:
#define assert(ignore) ((void)0)
Note that defining:
#define PRINTF(...) (void)0
instead of
#define PRINTF(...)
has an advantage. In the first case, you have an expression (like a function that returns no value) and so it is usable for example in a comma expression or in a conditional expression.
For example:
// Comma expression
printf("test"), PRINTF("Hi Dennis");
// Conditional expression
test-expr ? perror("Hello") : PRINTF("world");
This two expression statements are only valid with the former PRINTF definition (with (void) 0).
It'll be completely ignored, you can confirm this by looking at the assembly output (gcc -S will generate file.s, the asm output), compare with and without the (void)0 line and see that it is completely the same.
A half way decent compiler will optimise away dead (unreachable) code, so you can:
#ifdef DEBUG
#define PRINTF(...) if (1) { printf(__VA_ARGS__) ; }
#else
#define PRINTF(...) if (0) { printf(__VA_ARGS__) ; }
#endif
which has the big advantage of allowing the compiler to check the debug code, no matter whether you are working with/without your DEBUG turned on -- which reduces the risk of ending up with painful teeth marks in your backside.

Why doesn't #if preprocessor work?

With the following code, I always get "VGA" as output ,when I intend to get "NOT VGA"
#include<stdio.h>
#include<conio.h>
#define ADAPTER NVGA
#if ADAPTER==VGA
int main()
{
printf("VGA");
getch();
return 0;
}
#else
int main()
{
printf(" NOT VGA");
getch();
return 0;
}
#endif
Question is, where are VGA and NVGA defined?
If they are not defined, they will equal 0 according to C standard (N1570 - 6.10.1 Conditional inclusion - paragraph 4):
After all replacements due to macro expansion and the defined unary
operator have been performed, all remaining identifiers (including those lexically
identical to keywords) are replaced with the pp-number 0, and then each preprocessing
token is converted into a token.
Which means your comparison will be #if 0==0, which is identical to #if 1.
To fix this, you need to define both VGA and NVGA to have different values:
#define VGA 1
#define NVGA 2
There are two possibilities, and I can't tell which. The most likely is that, because neither NVGA nor VGA is a #defined macro, they are both evaluated as zero in #if and therefore considered to be equal. (This is a rule of the language.) The second possibility is that your system's stdio.h or conio.h defines NVGA to VGA.
To find out which, compile this program and see what happens:
#include <stdio.h>
#include <conio.h>
/* these numbers are chosen at random */
#define NVGA 8446
#define VGA 13060
#define ADAPTER NVGA
int main(void)
{
#if ADAPTER == VGA
puts("VGA");
#else
puts("NOT VGA");
#endif
getch();
return 0;
}
If it produces the output you expected (i.e. "NOT VGA"), your problem is the first one. If you get an error about redefining NVGA or VGA, your problem is the second one.
Because NVGA itself hasn't been defined. Instead try this:
#define NVGA 0
#define VGA 1
#define ADAPTER VGA
#if ADAPTER==VGA
/* insert VGA code here*/
#else
/* insert NVGA code here*/
#endif

#define IDENTIFIER without a token

What does the following statement mean:
#define FAHAD
I am familiar with the statements like:
#define FAHAD 1
But what does the #define statement without a token signify?
Is it that it is similar to a constant definition?
Defining a constant without a value acts as a flag to the preprocessor, and can be used like so:
#define MY_FLAG
#ifdef MY_FLAG
/* If we defined MY_FLAG, we want this to be compiled */
#else
/* We did not define MY_FLAG, we want this to be compiled instead */
#endif
it means that FAHAD is defined, you can later check if it's defined or not with:
#ifdef FAHAD
//do something
#else
//something else
#endif
Or:
#ifndef FAHAD //if not defined
//do something
#endif
A real life example use is to check if a function or a header is available for your platform, usually a build system will define macros to indicate that some functions or headers exist before actually compiling, for example this checks if signal.h is available:
#ifdef HAVE_SIGNAL_H
# include <signal.h>
#endif/*HAVE_SIGNAL_H*/
This checks if some function is available
#ifdef HAVE_SOME_FUNCTION
//use this function
#else
//else use another one
#endif
Any #define results in replacing the original identifier with the replacement tokens. If there are no replacement tokens, the replacement is empty:
#define DEF_A "some stuff"
#define DEF_B 42
#define DEF_C
printf("%s is %d\n", DEF_A, DEF_B DEF_C);
expands to:
printf("%s is %d\n", "some stuff", 42 );
I put a space between 42 and ) to indicate the "nothing" that DEF_C expanded-to, but in terms of the language at least, the output of the preprocessor is merely a stream of tokens. (Actual compilers generally let you see the preprocessor output. Whether there will be any white-space here depends on the actual preprocessor. For GNU cpp, there is one.)
As in the other answers so far, you can use #ifdef to test whether an identifier has been #defined. You can also write:
#if defined(DEF_C)
for instance. These tests are positive (i.e., the identifier is defined) even if the expansion is empty.
#define FAHAD
this will act like a compiler flag, under which some code can be done.
this will instruct the compiler to compile the code present under this compiler option
#ifdef FAHAD
printf();
#else
/* NA */
#endif

What's the use of defining ARGS in a different header file?

So I've been going through some code, and there's some things I can't understand.
I have two header files. One is called 'args.h' and in that there are these statements, amongst others:
#if (defined(__cplusplus) || defined(__STDC__) || defined(c_plusplus))
#define NEW_STYLE 1
#define VOID void
#define ARGS(parenthesized_list) parenthesized_list
#else
#define NEW_STYLE 0
#define VOID
#define ARGS(parenthesized_list) ()
#define const
#endif
#if !defined(EXIT_SUCCESS)
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
#endif
In the other header file, function prototypes are declared like this:
#if defined(__cplusplus)
extern "C" {
#endif
extern void yyerror ARGS((const char *s_));
extern int yylex ARGS((void));
extern int yyparse ARGS((void));
extern int yywrap ARGS((void));
#if defined(__cplusplus)
}
#endif
and a bunch of other stuff.
So my questions are:
1> What exactly does #define const do?
2> Why is arg declared in the other header file? Couldn't we simply declare the functions like a normal extern void a(const char *s__)? Or is this simply a preference of style?
Thanks.
This is to allow the code to compile with a pre-standard C compiler. It turns a function prototype into a function declaration, and simply removes const completely.
If you need to use a compiler so ancient that it doesn't understand prototypes or const, you have little choice but to use something like this. Otherwise, you're generally best off eliminating these horrible kludges.
20 years ago, code like this was common and necessary. It seems harder to excuse today, but I suppose there may still be a few platforms for which a reasonably modern compiler isn't available.
That are tweaks to make the code portable among compilers lacking this or that feature
is removing const everywhere (for sure not a good idea if you have a modern compiler)
this has to do with the ANSI C Syntax

Resources