Can preprocessor directive #include be disabled/excluded? - c

For example: If I have two .h files
process1.h and process2.h
and they contain two function with different output variables.
process1.h:
function(int var)
{
return 2*var;
}
process2.h:
function(int var)
{
return 10*var;
}
Can this be done in main.c:
int main()
{
int a = 2;
#include "process1.h"
printf("%d",function(a)); //output is 4
EXCLUDE #INCLUDE "process1.h" ????? <----can this be done in any way??
#include "process2.h"
printf("%d",function(a)); //output is 20
}

No, you cannot "un-include" a file. Think of all the preprocessor directives (lines starting with #) as happening before the actual C compiler even sees the source file. They just operate on the text of the file, and the preprocessor could be implemented as a separate step that just feeds new text into the actual compiler.
The best way to modify the actions of an include depending on the caller is to use further macros inside the included files, that you can #define before including them.
Still, your overall syntax is off, you can't (typically) nest functions in C.

No, and you should not try to write a program with two functions of the same name.
In the special case that the functions are actually defined in the header file (instead of just prototypes), you can do this:
#define function function_file1
#include "file1.h"
#undef function
#define function function_file2
#include "file2.h"
#undef function
int
main (void)
{
int a = 2;
printf ("%d\n", function_file1 (a));
printf ("%d\n", function_file2 (a));
}
BUT if you rename a function prototype then you haven't actually renamed the real function, so you'll get undefined symbol error when you link.
In any case, if you have two functions defined with the same name then it won't link anyway, not matter what else you do in the sources. (In C++, it is sometimes possible to define two things with the same name, but the One-Definition-Rule means the linker is allowed to assume they are both the same thing really and just pick one.)
This is why libraries are supposed to use names that won't be used elsewhere - usually by adding a common prefix to all symbol names (e.g. my_unique_lib_initialize()).

Why not use array of function pointers. Sure you need to initialize it at the start but I think it probably solves what you want to do.
int process1_function(int var);
int process2_function(int var);
int main(void)
{
int i, a = 10;
int (* functions[2])(int);
functions[0] = process1_function;
functions[1] = process2_function;
for(i=0; i < 2; i++)
{
printf("%d", (functions[i])(a));
}
return 0;
}
If you do not need to dynamically change which function you're going to call you can also just prefix the functions:
int process1_function(int var);
int process2_function(int var);
int main(void)
{
printf("%d",process1_function(a));
printf("%d",process2_function(a));
return 0;
}

Related

Displace function header with preprocessor directive

For debugging reasons i created the following code example: There is a function a() which is called by the function b(). I want to know the name of the function which calls a(). So i created the code below which is working fine:
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdarg.h>
uint8_t a(uint8_t k)
{
printf("function: a\n");
return k;
}
uint8_t a_debug( uint8_t j, char const *caller_name)
{
uint8_t rtv;
printf("a was called by %s\n", caller_name);
rtv = a(j);
return rtv;
}
#define a(x) a_debug(x,__func__)
void b()
{
uint8_t asdf;
asdf = a(5);
printf("asdf = %u", asdf);
}
int main(int argc, char **argv)
{
b();
return 0;
}
In a bigger software project with several c- and h-files I pasted the code
uint8_t a_debug( uint8_t j, char const *caller_name)
{
uint8_t rtv;
printf("a was called by %s\n", caller_name);
rtv = a(j);
return rtv;
}
#define a(x) a_debug(x,__func__)
right below the function a() to debug the function a(). I can build and execute the software-project but the function a_debug() is never entered. Instead of the function a() is directly executed. In which file or exactly where do I have to define the preprocessor directive #define a(x) a_debug(x,__func__) so that the compiler will displace a() with a_debug() function?
Preprocessor directives operate only in the translation unit where they appear.
A translation unit is the source file being compiled, including all the files it includes. To use a preprocessor macro, it must be defined in the translation unit. The way this is usually done is that a source file containing some functions named foo or related to some category or idea foo are defined in a file named foo.c, and declarations for those functions are put in a file named foo.h. The header file foo.h should provide whatever preprocessor macros, declarations, and other things are needed to use the facilities provided by foo.c.
To start, you can put your new function a_debug in the source file that contains a. Also, you can simplify it; there is no need for the variable rtv:
uint8_t a_debug(uint8_t j, char const *caller_name)
{
printf("a was called by %s.\n", caller_name);
return a(j);
}
Then, in the header file that declares a, you need to add two things. First, a declaration for a_debug:
uint8_t a_debug(uint8_t, char const *);
Second, a definition for the macro a:
#define a(x) (a_debug((x), __func__))
However, this is going to cause a problem. The source file defining a should include its own header file. (One reason for this is to allow the compiler to check for errors such as function declarations not matching function definitions.) But when it includes the header file, that will define the a macro, and then, when the function a is defined, the definition will be altered by the macro replacement, and the compiler will complain. One way around this is to put #undef a in the source file that defines a, after it includes its header file.
Also, since a_debug is so simple, you can define it as a static inline function in the header. Instead of putting the definition shown above in the source file and its declaration in the header file, put this in the header file:
static inline uint8_t a_debug(uint8_t j, char const *caller_name)
{
printf("a was called by %s.\n", caller_name);
return a(j);
}

Is there a way to expand macro based on command line arguments? [duplicate]

Following program compiles successfully and print 1000 without even calling a foo() function from our main() function. How is it possible?
#include<stdio.h>
void foo()
{
#define ans 1000
}
int main() {
printf("%d", ans);
return 0;
}
#defineis run by the preprocessor which is staged before the compiler. After the preprocessor is done, the code will look like this:
/* Everything that is inside stdio.h is inserted here */
void foo()
{
}
int main() {
printf("%d", 1000);
return 0;
}
And this is what actually get compiled.
The preprocessor is very important to make header files work. In them, you see this structure:
#ifndef foo
#define foo
/* The content of the header file */
#endif
Without this, the compiler would complain if a header file is included more than once. You may ask why you would want to include a header file more than once. Well, header files can include other header files. Consider this macro, which is useful for debugging. It prints the name of the variable and then the value. Note that you would have to do a separate version for different types.
#define dbg_print_int(x) fprintf(stderr, "%s = %d", #x, x)
This is pretty versatile, so you may want to include it in a header file for own use. Since it requires stdio.h, we include it.
/* debug.h */
#include <stdio.h>
#define dbg_print_int(x) fprintf(stderr, "%s = %d", #x, x)
What happens when you include this file and also include stdio.h in you main program? Well, stdio.h will be included twice. That's why debug.h should look like this:
/* debug.h */
#ifndef DEBUG_H
#define DEBUG_H
#include <stdio.h>
#define dbg_print_int(x) fprintf(stderr, "%s = %d", #x, x)
#endif
The file stdio.h has the same construct. The main thing here is that this is run before the compiler. The define is a simple replacement command. It does not know anything about scope or types. However, as you can see here, there is some basic logic built into it. Another thing that the preprocessor does is to remove all the comments.
You can read more about the C preprocessor here: http://www.tutorialspoint.com/cprogramming/c_preprocessors.htm
The #define is processed by the preprocessor before the compiler does anything. It is a simple text replacement. The preprocessor doesn't even know if the line of code is inside or outside a function, class or whatever [Ref: https://stackoverflow.com/a/36968600/5505997]. Clearly you do not need to call the function to set the value and obviously you will not get any error during compile.
As others have stated, #define is a preprocessor directive, not C source code. See Wiki here.
Point being, in your code #define ans 1000 is not a variable definition, meaning that even if you were calling foo() in the main, you would still not be setting "ans" at runtime, because it is simply not a variable. It is just telling the preprocessor what to do with the "label" "ans", when it finds it in your source code.
In this example, the main() will essentially be calling an empty foo() function:
int main()
{
foo(); // Calls an empty function
printf("%d", ans); // ans will have been substituted by 1000 by the time you start executing you code
return 0;
}
The definition of "ans" will simpy not exist anymore by the time you start executing you main(). This is what the preprocessor does (in part). It finds all the #defines declared in your entire source code and tries to find places in your code where you have used these defines. If you have not used them, it moves on (don't care), if you have, it substitutes the label by the actual defined value.

Why does this variable change when passed to a function

I've recently started working on a chess engine, and am having trouble with a function to apply moves to the board. I have a structure type for the board state, and another to store moves. These are both in my header file below.
#ifndef DECLARATIONS_H
#define DECLARATIONS_H
#include <stdbool.h>
#define BOARD_SIZE 120
typedef struct move {
int startingSquare;
int endingSquare;
int promotionPiece;
} move;
typedef struct boardState {
int board[BOARD_SIZE];
bool whoseTurn;
int ply;
int threeMoveRuleCount;
int fiftyMoveRuleCount;
bool whiteCastleKingside;
bool whiteCastleQueenside;
bool blackCastleKingside;
bool blackCastleQueenside;
int enPassant;
float evaluation;
move previousMove;
} boardState;
boardState currentBoard;
#endif
Main.c calls the "Process Move" function from movegeneration.c. It passes one of the boardstate types and one of the move types:
#include <stdio.h>
#include <string.h>
#include "declarations.h"
int main () {
move firstMove;
firstMove.startingSquare = 35;
firstMove.endingSquare = 55;
firstMove.promotionPiece = 0;
printf("Value of firstMove.endingSquare: %d\n", firstMove.endingSquare);
printf("Value of firstMove.startingSquare: %d\n", firstMove.startingSquare);
printf("Value of firstMove.promotionPiece: %d\n", firstMove.promotionPiece);
processMove(currentBoard, firstMove);
return 0;
}
Below is movegeneration.c, which contains the function to process the move:
#include <stdio.h>
#include "declarations.h"
boardState processMove(boardState, move);
boardState processMove(boardState oldBoardState, move moveToApply) {
boardState newBoardState = oldBoardState;
printf("Value of moveToApply.endingSquare: %d\n", moveToApply.endingSquare);
printf("Value of moveToApply.startingSquare: %d\n", moveToApply.startingSquare);
printf("Value of moveToApply.promotionPiece: %d\n", moveToApply.promotionPiece);
return newBoardState;
}
And here's the program output:
Value of firstMove.endingSquare: 55
Value of firstMove.startingSquare: 35
Value of firstMove.promotionPiece: 0
Value of moveToApply.endingSquare: 0
Value of moveToApply.startingSquare: 55
Value of moveToApply.promotionPiece: 1996058613
This isn't all the code from the .c files, but it's everything relevant here. What makes this bizarre is that the values of the move change as soon as I call the function. When I put all the code into one large .c file and compile that way, the problem goes away, but I'm trying to keep the code separate to stay organized. This one has me completely stumped. I'd appreciate any help!
There's at least 2 problems here, causing undefined behaviour.
Firstly, there are multiple definitions of boardState currentBoard; . Remember that #include is a plain text replacement, so both of your c files end up with a definition of that object. See here for an in-depth explanation with examples.
If you want to have a global object accessible from multiple translation units then the header file should contain a declaration only (i.e. prepend extern to the current line), and exactly one of the .c files should contain the definition.
Secondly, in main() you call an undeclared function processMove. If you compile in standard mode then the compiler should generate an error message. This is likely the cause of your symptoms, and I would strongly recommend invoking your compiler in modern standard mode with a high diagnostic level, as it would have saved you a lot of time to find out about this problem sooner.
To fix this, the declaration boardState processMove(boardState, move); should be in declarations.h.

Why functions defined in the same file as main can not be called from other files in the program?

At a rainy weekend, I was reading K. N. King's C Programming: A Modern Approach.
And at page 359, it says that “It is possible that there are other functions in the same file as main, so long as they are not called from other files in the program.”
I do not know the reason and I try it like this:
// a.h
int sum(void);
int sub(void);
// a.c
#include <stdio.h>
#include "a.h"
#include "b.h"
int a = 0;
int b = 1;
int main(int argc, char const *argv[])
{
printf("sum = %d,\nsub = %d,\ndbl= %d\n", sum(), sub(), dbl() );
return 0;
}
int sum()
{
return ( a + b );
}
int sub()
{
return ( a - b );
}
// b.h
int dbl(void);
// b.c
#include "a.h"
#include "b.h"
int dbl()
{
return ( sum() + sub() );
}
Then I compile it with
gcc -a.exe a.c b.c
at cygwin. Then run a.exe as
./a.exe
Every thing goes well with the output "sum = 1, sub = -1, dbl = 0". So, who gets wrong, Mr K. N. King, or I ?
The cited part is program design advise.
There is nothing in the C language preventing you from putting a function definition anywhere in any linked file, as long as a function declaration is visible to the caller.
But it is very bad practice to have specific files call functions in what should be the top level of the application design. The key to good program design is to write autonomous code modules that only does their designated task and knows as little about the rest of the program as possible.
Having various parts of the application call other, non-related parts is sloppy, messy and leads to tight coupling. Apart from the program turning out a mess to read and maintain, tight coupling also means that bugs will escalate all over the program. Meaning that when you write a bug in one module, you will break completely non-related parts of the program.
To prevent such things, functions located in main should only be helper functions called by main itself, if such functions are needed. They should be declared as static functions to block other parts of the program from getting access to them.
In "a.h" include the following line:
extern int a;
extern int b;
Then retry your code and check the output.

How to undef a library function to use our version of same function

How to undef a library function to use my version of same function. Notice that I need to include the header file for other functions of same file. So not including is it not an option. Is there any way to use it without changing the name?
You can do the following:
#define function_name function_name_orig
#include <library.h>
#undef function_name
int function_name() {
/* ... */
}
This way the function will not be defined by the header, since it will be replaced by function_name_orig. Implementations of getters or setters in the header file may continue to work - even if they use function_name, since those calls will also be replaced.
For gcc, #undef seems to cut it, so long as you're keeping the same prototype for the function. For example:
#include <stdio.h>
#undef scanf
int scanf(const char * s, ...)
{
printf(s);
return 0;
}
int main()
{
scanf("hello\n");
return 0;
}
This compiles without warnings with -Wall, but if you want scanf to have a prototype of (say) void scanf(void) it will give errors.

Resources