Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "disable" macros imported from C-Header

Class A uses a library written in C. This library provides some data types and constants which are used in A. Unfortunately, the library also defines macros in its header file, which collide with my C++ code in main.cpp or in other classes using A.

How can I prevent macros of c_library.h being executed when A.h is included somewhere? I would also be open for architectural changes, but I would prefer not to touch the C library.

Of course, there's the #undef directive. But this would mean a lot of manual work for every macro or for every collision. (Ok, there are not too many - but hey, this must be possible more elegant?)

Code:

//main.cpp

#include "A.h"

...
A a(...)
...
std::max(x, y); // oops, problem since max is defined as macro in c_library.h
...

//A.h
#include "c_library.h"

class A{
public:
    A(...);
    static void callbackForCLibrary(datatypeOfCLibrary d){...}
private:
    private datatypeOfCLibrary1;
    private datatypeOfCLibrary2;
}
like image 468
Michael Avatar asked Jul 30 '14 20:07

Michael


People also ask

Should macros be in header file?

The Google C++ Style Guide guide advises that macros must not be defined in a . h (header) file.

In which header file is the macro defined?

A header file is a file with extension . h which contains C function declarations and macro definitions to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that comes with your compiler.

What is pre processor in C language?

The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs.


1 Answers

You already know about the #undef option, which would do what you need.

There is another option however. You could completely hide the fact that your A uses library C from your users: Define your own types and interface in the header and class definition of A and remove the library include from your A header. Then in your implementation file you can include the library header and utilize the library in whatever manner is needed, all the while hiding the include of the c_library.h from your users. This has the added advantage of reducing the coupling between your class users, your class, and the library that it depends on.

like image 144
Mark B Avatar answered Oct 12 '22 14:10

Mark B