How to provide an option to a C library via a macro - c

I have the following source named lcd.c.
#include <stdio.h>
#include "lcd.h"
void print_mode(void)
{
printf("%d\n",LCD_MODE);
}
The header lcd.h contains the definition for LCD_MODE as follows.
#ifndef LCD_H
#define LCD_H
#include "util.h"
#ifndef LCD_MODE
#define LCD_MODE LCD_MODE_8BIT
#endif
void print_mode(void);
#endif /* LCD_H */
The file util.h contains
#ifndef UTIL_H
#define UTIL_H
#define LCD_MODE_8BIT 1
#define LCD_MODE_4BIT 0
#endif /* UTIL_H */
lcd.c will be compiled separately as part of some library. I want to use it with an application main.c as follows.
#include "util.h"
#define LCD_MODE LCD_MODE_4BIT
#include "lcd.h"
int main(void)
{
print_mode();
return 0;
}
The desired outcome is to print 0 as per the definition of LCD_MODE_4BIT in main.c. However, 1 is printed because the header file sees that LCD_MODE is not defined during the preprocessing for lcd.c. How should I go about passing the LCD_MODE option to print_mode() through the main application?

if you cannot recompile lcd.c you cannot use a macro in another source file, because lcd.o already has the value hardcoded.
You could create a static variable (which defaults to LCD_MODE) that you can change using a setter:
#include <stdio.h>
#include "lcd.h"
static int the_mode = LCD_MODE;
void print_mode(void)
{
printf("%d\n",the_mode);
}
void set_mode(int new_mode)
{
the_mode = new_mode;
}
lcd.h should contain the prototype for the new configuration function BTW:
void set_mode(int new_mode);
then in your main, you can:
set_mode(LCD_MODE);
(or drop that LCD_MODE macro everywhere because it solves nothing and adds to the confusion)

Related

Do I need to include imports in a header file with 'special types'?

Let's take the following example:
// hash.h
#ifndef _HASH_H_
#define _HASH_H_
/* A few prime number helpers */
bool is_prime(int x);
#endif
Because this header file uses the bool object, do I need to add #include <stdbool.h>, or is it enough for the hash.c file to import it. Why or why not?
Your header file should include it if it needs it.
Otherwise you'd be relying on the include order of the file includeing your header:
// works
#include <stdbool.h>
#include "hash.h"
// doesn't work -- bool not defined yet when hash.h is processed
#include "hash.h"
#include <stdbool.h>

How to include files in C, globally?

My compilation order is :
core1.c
top.c
core1.c contents :
#include "header1.h"
#include "header2.h"
void function1() {
---- }
void function2() {
---- }
header1.c contents function declarations, enums, includes :
#include comdef.h
void function1();
void function2();
top.c contents :
#include "header1.h"
#include "header2.h"
void main() {
function1();
function2();
}
I will add more headers and more core C files into my project. Each core.c file needs the same header files. How to get this all working, without the need to put #include header1/2.h in each core1.c, core2.c etc, and include these headers only in main.c ?
You can use a global header including all files
/* glob.h */
#ifndef GLOB_H
#define GLOB_H
#include "header1.h"
#include "header2.h"
#endif /* GLOB_H */
and in your main file
#include "glob.h"
Even if this is considered bad style, there are several projects using this approach, i.e. gtk
Use one header for each source file:
core1.h:
#ifndef _CORE1
#define _CORE1
#include comdef.h
void function1();
void function2();
#endif
core1.c:
#include "core1.h"
void function1() {
---- }
void function2() {
---- }
top.c:
#include "core1.h"
void main() {
function1();
function2();
}

C preprocessor #error in header file included in multiple source files

I have two source files, main.c and datamgr.c - and two header files, config.h and datamgr.h
The testing system we're using expects these files, and only these files.
main.c:
#include "datamgr.h"
#include "config.h"
int main() {
custom_type a = 1;
a = foo();
return 0;
}
datamgr.c:
#include "datamgr.h"
#include "config.h"
custom_type foo() {
custom_type a = 1;
return a;
}
datamgr.h:
#ifndef DATAMGR_H
#define DATAMGR_H
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
custom_type foo();
#endif
config.h:
#ifndef CONFIG_H
#define CONFIG_H
#ifndef SET_MAX_TEMP
#error "Max temperature not set."
#endif
#ifndef SET_MIN_TEMP
#error "Max temperature not set."
#endif
typedef custom_type uint16_t
#endif
Now, the problem is that I can only define SET_MAX_TEMP and SET_MIN_TEMP in main.c, but both main.c and datamgr.c need both the header files. So if I leave them undefined in datamgr.c I get a compiler error. However, if I do define them in datamgr.c and later overwrite them in main.c, I get a different compiler error.
Please, any assistance as to how to get this horrible setup to work would be greatly appreciated.
You can pass these defines directly while compiling:
gcc -DSET_MAX_TEMP -DSET_MIN_TEMP <your files>
In datamgr.c do:
#define SET_MAX_TEMP
#define SET_MIN_TEMP
#include "datamgr.h"
#include "config.h"
#undef SET_MAX_TEMP
#undef SET_MIN_TEMP
In a comment, you said:
Because main.c is the file that our testing system uses to implement the test scenarios.
In that case, make sure that the testing system defines those macros in the command line of the compiler for every file being compiled.

Include Guard still inserting Global Variables

I have 3 *.c files (file1.c, file2.c and file3.c) and 1 *.h file (file3.h) in a project (Visual Studio).
/*******************************
file3.h
********************************/
#ifndef FILE3_H
#define FILE3_H
int gintVariable = 400;
#endif
/*******************************
file1.c
********************************/
#include "file3.h"
#include <stdio.h>
#include <conio.h>
int modifyGlobalVariable(void);
void printGlobalVariable(void);
int main(void)
{
modifyGlobalVariable();
printGlobalVariable();
printf("Global variable: %d\n", gintVariable++);
getch();
return 0;
}
/*******************************
file2.c
********************************/
#include "file3.h"
int modifyGlobalVariable(void)
{
return gintVariable++;
}
/*******************************
file3.c
********************************/
#include "file3.h"
#include <stdio.h>
void printGlobalVariable(void)
{
printf("Global: %d\n", gintVariable++);
}
When I build the solution in VS, it is giving error as "_gintVariable already defined in file1.obj".
I did check in the pre-processor output, the gintVariable is included in all the *.c files even though I have included include guards.
What mistake I am doing?
You should use 'extern' while declaring a global variable in header file.
Define it in any one of *.c file.
This should fix the issue.
For more on header files, read
How do I use extern to share variables between source files?
Including guards prevents multiple inclusion (or, more precisely, multiple compilation of the .h file content) in a single translation unit.
It is useful against this problem:
/* glob.h */
#ifndef H_GLOB
#define H_GLOB
struct s { int i; };
#endif
/* f.h */
#ifndef H_F
#define H_F
#include "glob.h"
struct s f(void);
#endif
/* g.h */
#ifndef H_G
#define H_G
#include "glob.h"
struct s g(void);
#endif
/* c.c */
#include "f.h" /* includes "glob.h" */
#include "g.h" /* includes "glob.h" */
void c(void) {
struct s s1 = f();
struct s s2 = g();
}
The inclusions is like a diamond:
glob.h
/ \
f.h g.h
\ /
c.c

How can I stop #including redundant headers when I use header files like these?

So I'm still getting used to modular programming, and want to make sure I'm adhering to best practices. If I have the two module header files below, will the the headers #included by each file (for example "mpi.h") be included multiple times? Is there a proper way to account for this?
Also, my module headers typically look like these examples, so any other criticism/pointers would be helpful.
/* foo.h */
#ifndef FOO_H
#define FOO_H
#include <stdlib.h>
#include "mpi.h"
void foo();
#endif
and
/* bar.h */
#ifndef BAR_H
#define BAR_H
#include <stdlib.h>
#include "mpi.h"
void bar();
#endif
And use the sample program:
/* ExampleClient.c */
#include <stdlib.h>
#include <stdio.h>
#include "mpi.h"
#include "foo.h"
#include "bar.h"
void main(int argc, char *argv[]) {
foo();
MPI_Func();
bar();
exit(0)
}
What do you mean by 'include'? The preprocessor statement #include file copies the contents of file and replaces the statement with these contents. This happens no matter
If by 'include' you mean "the statements and symbols in these files will be parsed multiple times causing warnings and errors", then no, the include guards will prevent that.
If by 'include' you mean "some part of compiler will read some part of these files", then yes, they'll be included multiple times. The preprocessor will read the second inclusion of the file and replace it with a blank line because of the include guards, which incurs a tiny overhead (the file is already in memory). Modern compilers (GCC, not sure about others) will probably be optimized to avoid this, however, and note that the file has include guards on the first pass and simply discard future inclusions, removing the overhead - Don't worry about speed here, clarity and modularity are more important. Compilation is a time-consuming process, for sure, but #include is the least of your worries.
To better understand include guards, consider the following code sample:
#ifndef INCLUDE_GUARD
#define INCLUDE_GUARD
// Define to 1 in first block
#define GUARDED 1
#endif
#ifndef INCLUDE_GUARD
#define INCLUDE_GUARD
// Redefine to 2 in second block
#define GUARDED 2
#endif
After (the first pass of) preprocessing, what will GUARDED be defined to? The preprocessor statement #ifndef or its equivalent, #if !defined() will return false if their argument is indeed defined. Therefore, we can conclude that the second #ifndef will return false, so only the first definition of GUARDED will remain after the first pass of the preprocessor. Any instance of GUARDED remaining in the program will be replaced by 1 on the next pass.
In your example, you've got something slightly (but not much) more complicated. Expanding all the #include statements in ExampleClient.c will result in the following source: (Note: I indented it, but that's not normal style for headers and the preprocessor won't do it. I just wanted to make it more readable)
/* ExampleClient.c */
//#include <stdlib.h>
#ifndef STDLIB_H
#define STDLIB_H
int abs (int number); //etc.
#endif
//#include <stdio.h>
#ifndef STDLIB_H
#define STDLIB_H
#define NULL 0 //etc.
#endif
//#include "mpi.h"
#ifndef MPI_H
#define MPI_H
void MPI_Func(void);
#endif
//#include "foo.h"
#ifndef FOO_H
#define FOO_H
//#include <stdlib.h>
#ifndef STDLIB_H
#define STDLIB_H
int abs (int number); //etc.
#endif
//#include "mpi.h"
#ifndef MPI_H
#define MPI_H
void MPI_Func(void);
#endif
void foo(void);
#endif
//#include "bar.h"
#ifndef BAR_H
#define BAR_H
//#include <stdlib.h>
#ifndef STDLIB_H
#define STDLIB_H
int abs (int number); //etc.
#endif
//#include "mpi.h"
#ifndef MPI_H
#define MPI_H
void MPI_Func(void);
#endif
void bar(void);
#endif
void main(int argc, char *argv[]) {
foo();
MPI_Func();
bar();
exit(0); // Added missing semicolon
}
Go through that code and note when various definitions are performed. The result is:
#define STDLIB_H
int abs (int number); //etc.
#define STDLIB_H
#define NULL 0 //etc.
#define MPI_H
void MPI_Func(void);
#define FOO_H
void foo(void);
#define BAR_H
void bar(void);
With respect to your request for other criticism/pointers, why are you #including stdlib.h and mpi.h in all your headers? I understand that this is a stripped down example, but in general, header files should only include files necessary for the declaration of their contents. If you use a function from stdlib or call MPI_func() in foo.c or bar.c, but the function declarations are simply void foo(void), you shouldn't include these files in the header function. For example, consider the following module:
foo.h:
#ifndef FOO_H
#define FOO_H
void foo(void);
#endif
foo.c:
#include <stdlib.h> // Defines type size_t
#include "mpi.h" // Declares function MPI_func()
#include "foo.h" // Include self so type definitions and function declarations
// in foo.h are available to all functions in foo.c
void foo(void);
size_t length;
char msg[] = "Message";
MPI_func(msg, length);
}
In this example, the implementation of foo() requires stuff from stdlib and mpi, but the definition does not. If foo() returned or required a size_t value (typedef'ed in stdlib), you'd need to #include stdlib in the .h file.
Mostly no, with a bit 'yes'. Your header files will be 'read' more than once but at second and later time the preprocessor will cut off all the contents. This implies that it won't waste your compiler's time and also #includes inside your #ifdef blocks will be done only once (per header file).
It's a good practice. Myself, I also add the following line before #ifdefs:
#pragma once
When supported by the particular compiler, it guarantees that the file will actually be read only once. I think it's a little bit more optimal that way.
So, to sum up:
header guards like you are using prevent compiler from interpreting the header contents more than once but possibly can cause the preprocessor to parse it more than once (which is not a big problem),
#pragma once causes the particular header file to be read only once.
When using both, #pragma once should be in effect if supported by compiler; if not, header guards will apply.
1) GOOD: you have an "include guard". "stdlib.h", "mpi.h" and "void foo()" are only seen by the compiler the first time you #include "foo.h"
/* foo.h */
#ifndef FOO_H
#define FOO_H
#include <stdlib.h>
#include "mpi.h"
void foo();
#endif
2) BAD: This will #include the entire contents of "foo.h" every time you use it:
/* foo.h */
#include <stdlib.h>
#include "mpi.h"
void foo();
3) By #include", I mean "once per compilation unit" (i.e. the same .c source file).
This mainly "protects" against a header (foo.h) calling another header ("bar.h) which might recursively call the first header.
Every different compilation unit that #includes foo.h will always get "stdlib.h", "mpi.h" and "void foo()". The point is that they'll be seen only once - not multiple times in the same compilation unit.
4) This is all "compile-time". It has nothing to do with libraries (which are "link time").
Yes, mpi.h will be included multiple times (as will stdlib.h); if mpi.h has include guards similar to foo.h and bar.h, then it won't be an issue.

Resources