Search code examples
c++g++polyglot

Warning inside a preprocessor "#if 0" section


So I have a polyglot header file that is included/imported from Python and C++. The part I'm insterested in looks like so:

#pragma once 

#if 0
"""
#endif
constexpr int 
#if 0
"""
#endif
val = 2;

The idea is that Python code that imports it will see:

"""
constexpr int 
"""
val = 2;

while C++ code that inculdes it will see

constexpr int 
val = 2;

What I find strange I that I get the following warning (only when compiling in Linux):

warning: missing terminating " character

And this can be shown in simple c++ Demo (where the header is not included but defined inline)

The thing is that the """ sequence is mentioned inside an #if 0 / #endif block. Why am I getting warnings for something that should be preprocessed out, and is there a way to avoid them?


Solution

  • Discussion about whether this is a logical thing to do for OP aside:

    For the purpose of a polyglot, this works without warnings:

    #if 0
    """"
    #endif
    
    constexpr int
    
    #if 0
    " """
    #endif
    val = 2;
    

    The C++ compiler is now happy about matched quotes and for the python interpreter, the docstring now starts with a " and ends in " . The last space in the docstring is needed for python to recognize the triple quotes at the end.