Armen Babakanian
Armen Babakanian

Reputation: 2345

C header defines in a C++ source cause compile error

I have a library written by a not very meticulous coder, which includes the following code in a C header file:

/* SomeCHeaderFile.h */
...
#define local static  
#define package       
#define global        

When this file is included in a C++ header, for example: EDIT: I forgot to mention that I include the header like so:

// SomeCPlusplusSourceFile.cpp
extern "C" {
   #include "SomeCHeaderFile.h"
}
...

the compiler gives the following error:

error: constructor cannot be static member function
error: 'std::locale::locale(const std::locale&)' cannot be overloaded
error: with 'std::locale::locale(const std::locale&)'

I only say the coder was not meticulous because she/he never tested it in a C++ code. But I don't know the reasoning behind this to why is this causing the build to fail?

gcc version 4.4.3 | ubuntu linux

Upvotes: 0

Views: 202

Answers (2)

Prabhu
Prabhu

Reputation: 3541

You can use C header files in CPP files as follows:

extern "C" {

//Headers go here

}

More details here:

In C++ source, what is the effect of extern "C"?

Upvotes: 1

jxh
jxh

Reputation: 70502

It seems the troublesome C header file is redefining tokens in use by the standard C++ header files. If you want to use the C header file in your C++ code, you may be required to include it after the standard header files to prevent this kind of problem.

This may not sufficiently guard you from problems if the C++ code defines its own macros that also redefine the same tokens. If that happens, you will have to segregate your C++ code with files dedicated to C++ that uses the troublesome C header file and C++ code that does not. The C++ code that does use the troublesome C header file makes sure to not use any C++ header file that would cause problems.

Upvotes: 2

Related Questions