简体   繁体   中英

C, #include and #define override

I have a library as this:

mylib
  |__ device
        |__ lcd.h
        |__ lcd_config.h
        |__ lcd.c

.

// File lcd.h
#include lcd_config.h

void function initLcd();
void function writeLcd();

.

// File lcd.c
#include lcd.h

void function writeLcd(){
     // some code
}

.

// File lcd_config.h inside mylib
#ifndef lcd_config_H
#define lcd_config_H

#define TEST 10

#endif

I want to use the library in a project, but I want to redefine the configuration file.

myproject
    |__ lcd_config.h
    |__ mylcd.c
    |__ main.c

.

// File lcd_config.h inside myproject(at main.c level)
#ifndef lcd_config_H
#define lcd_config_H

#define TEST 20

#endif

.

// File mylcd.c
#include lcd.h

void function initLcd(){
     printf("%d", TEST);
}

.

// File main.c
#include "device/lcd.h"

int main(void) {
    initLcd(); // print 10
}

.

// File main1.c
#include "lcd_config.h"
#include "device/lcd.h"

int main(void) {
    initLcd(); // print 10 too
}

In my project i want that TEST = 20, how can i achieve this?

UPDATE

Look at file now, this is my real case.

To print TEST=20 i have to put #include lcd_config.h before #include lcd.h inside mylcd.c . If i put it in main file(like main1.c) 10 will be print, si think preprocessing look before inside mylcd.h that main.c.

Thanks

Include the header that defines the TEST to 20 first. Beware that the #ifndef conditions will prevent the second header from actually doing anything, this is why in your case the value of TEST remains 10.

In some more detail, the block below says "this header should only be included in the project once". Defining the second header with the same clause in it will not change things if that header is included after the first one.

#ifndef lcd_config_H
#define lcd_config_H
...
#endif

I think the whole situation looks strange, though, there shouldn't be too headers with exactly the same name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM