Fabricio
Fabricio

Reputation: 7935

How to implement a macro in .c but expose it for use in the .h file

I don't know if this is possible, nor even if it is correct, but I have a macro defined in a .c file and now I want to expose that macro, so I need put it in the .h file. But I dont want to expose how it is implemented, just the signature for use.

//.c
#define sayhi() printf("hi");

//.h
sayhi()

//another.c
int main(...) {
    sayhi();
}

Upvotes: 2

Views: 481

Answers (3)

Chris Barrett
Chris Barrett

Reputation: 3385

The preprocessor doesn't have anything like the linkage semantics of C source code, so what the macro expands to will depend on the last definition seen by the preprocessor. For this reason, you really need to keep the macro's definition in a header.

Two approaches come to mind:

  1. delegate as much of the macro's functionality as possible to a function, and declare the macro and function prototype in the header. You can put the implementation of the function in a source file.

  2. put the macro's definition in a private header.

// hi_internal.h

#define sayhi() printf("Hello, world!");

Include this in your public header with an explanatory comment.

// hi.h    

#define sayhi()    

// hi_internal redefines the above macros. 
// It must be included after the above definitions.
#include "hi_internal.h"

Upvotes: 2

selbie
selbie

Reputation: 104579

Don't make it a macro then. Just make it a function call.

Your .h file:

extern void DoSomething(int x, int y, int z);

Your .c file:

void DoSomething(int x, int y, int z)
{
    // your code goes here.
}

Upvotes: 7

kfsone
kfsone

Reputation: 24269

Macros don't have signatures the way functions do, they only exist for the duration of the pre-processing phase. You'll either have to make it a function or make the implementation a function.

Upvotes: 5

Related Questions