Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 568
Ranul Avatar asked Sep 20 '25 02:09

Ranul


1 Answers

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)

like image 170
Jean-François Fabre Avatar answered Sep 22 '25 20:09

Jean-François Fabre