[Python-Dev] #ifdef __cplusplus?

Alexander Belopolsky alexander.belopolsky at gmail.com
Fri Jan 2 06:17:24 CET 2009

On Thu, Jan 1, 2009 at 11:05 PM, Christian Heimes <lists at cheimes.de> wrote:
> You might be interested in the bug report
> http://bugs.python.org/issue4665. Skip pointed out that Python 2.6 no
> longer compiles with a C++ compiler due to missing casts. C++ is more
> restrict when it comes to implicit casts from (amongst others) void
> pointers.
Since that issue is closed, I have created
http://bugs.python.org/issue4805 with a patch that restores C++
compilability of the core and a few standard modules.

> Martin is against the necessary changes. I don't really care about it.
> If somebody wants to tackle the issue I'm fine with sprinkling some type
> casts over the code.
I've listed the following arguments in support maintaining C++
compilability on the bug tracker:

1. It is hard to verify that header files are compilable if source code
is not.  With compilable source code, CC=g++ ./configure; make will
supply an adequate test that does not require anything beyond a standard

2. Arguably, C++ compliant code is more consistent and less error prone.
For example, "new" is a really bad choice for a variable name regardless
of being a C++ keyword, especially when used instead of prevailing "res"
for a result of a function producing a PyObject. Even clearly redundant
explicit casts of malloc return values arguably improve readability by
reminding the type of the object that is being allocated.

3. Compiling with C++ may reveal actual coding errors that otherwise
go unnoticed.  For example, use of undefined
PyLong_BASE_TWODIGITS_TYPE in Objects/longobject.c.

4. Stricter type checking may promote use of specific types instead of
void* which in turn may help optimizing compilers.

5. Once achieved, C++ compilability is not that hard to maintain, but
restoring it with patches like this one is hard because it requires
review of changes to many unrelated files.

Note that this discussion has deviated from OP's original question.
While I argue that C++ compilability of source code is good thing, I
agree with OP that wrapping non-header file code in extern "C" {} is
bad practice.  For example, the only reason Objects/fileobject.c does
not compile without extern "C" {} is because fclose is declared inside
PyFile_FromString as follows:

 PyObject *
 PyFile_FromString(char *name, char *mode)
 	extern int fclose(FILE *);

I would rather #include <stdio.h> at the top of the file instead.

More information about the Python-Dev mailing list