Home > Software design >  Use a macro both in implementation and header and then undefine it
Use a macro both in implementation and header and then undefine it

Time:10-14

I have a macro that should be used both in my source file and header one. However I don't wan't other code linked to the final object to access that macro (more than anything else I don't want the macro to go causing unexpected errors in other files). I thought about using a macro with a long and complicated name that will be unlikely used from other code, however this solution kinda looks ugly to me. Obviously the most simple solution would be to undefine the macro in some way, however if I define the macro in the header and then undefine it – I think – I won't be able to access it anymore from the source file. What should I do?

// hi.h
#define string char *

void greet(string x);
// hi.c
#include "hi.h"

void greet(string x) {
    printf("Hi!");
}

Okay, don't kill me, this was just an example, i know #define string char * is horrible.

Last minute thought: Maybe I can underfine the macro at the end of the source file, is this acceptable to do?

CodePudding user response:

I guess you could conditionally "undefine" macro at the end of the header when the a magic macro is not defined. The blessed source file would have to define this macro prior to including a header.

// header.h
...
#ifndef MAGIC_MACRO
#undef string
#endif

// common source
#include "header.h"

// blessed source
#define MAGIC_MACRO
#include "header.h"

This solution will work great as long as no macro defined inside the header uses string macro.

CodePudding user response:

What should I do?

Pick option 1 a macro with a long and complicated name that will be unlikely used from other code as it's the simplest and most obvious. Do not use a complicated name - just use a name so that you and other developers will know it's a private symbol, that's all.

// hi.h

// this macro is private
#define _lib_string  char *

Remember about reserved words. Example: https://github.com/GNOME/glib/blob/main/glib/glib-private.h#L32 .

he most simple solution would be to undefine the macro in some way, however if I define the macro in the header and then undefine it – I think – I won't be able to access it anymore from the source file

If you go this way, you'll end up with spaghetti code, where some global state affects what you have. For example:

// hi.h
#define string char *

void greet(string x);

#ifndef FROM_HI_C
#undef string
#endif

// hi.c
#define FROM_HI_C
#include "hi.h"

void greet(string x) {
    printf("Hi!");
}

Maybe I can underfine the macro at the end of the source file, is this acceptable to do?

Other files see only the header file - they are unaffected by anything in the source file.

  •  Tags:  
  • c
  • Related