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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With