Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid a globally defined C macro of `Status` from `Xlib.h`?

Tags:

c++

macros

I'm using some opengl library which includes /usr/include/X11/Xlib.h, in this header file, line 83, Status is defined as a macro:

#define Status int

I'm also using google's protobuf, which has code like this:

 LogMessage& operator<<(const ::google::protobuf::util::Status& status);

In this case, what should I do use both of them?


2 Answers

The C++ mechanism around this problem is to use namespaces.

In any even you are going to have to get rid of the macro and put this after including the notoriously problematic X code.

#if defined (Status)
# undef Status
typedef int Status ;
#endif

That might solve the problem by itself.

like image 127
user3344003 Avatar answered Nov 20 '25 13:11

user3344003


Problem here is dependency management of your project.

If you would have well organized project, then code generated by protobuf would be visible only in network layer of your application and code handling UI would not see that part of code.

And vice versa UI should be isolated so X11 headers should not leak into business logic or network layer. Here is nice Uncle Bob talk explaining the issue and how to handle it.

Since fixing dependencies in already written project is hard. You are probably forced to use undefine trick in alternative answer. Anyway first you should check if it is possible isolate headers from each other when included to translation units.

One of way to improve such isolation is clean up header files. Forward declare as much as possible and include minimum number of headers for other headers. If you do it well protobuf headers and X11 headers will not meet in same source file which is nicer solution. There is nice tool to achieved that. Include what you use. There is a great chance that this will fix your problem and another gain is that it will improve your project build times.

like image 42
Marek R Avatar answered Nov 20 '25 12:11

Marek R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!