c++cstdmixing

Calling C++ standard header (cstdint) from C file


I have an external library written in C++ such as

external.h

#ifndef OUTPUT_FROM_CPP_H
#define OUTPUT_FROM_CPP_H

#include <cstdint>
extern "C" uint8_t myCppFunction(uint8_t n);

#endif

external.cpp

#include "external.h"
uint8_t myCppFunction(uint8_t n)
{
    return n;
}

Currently I have no choice but use this C++ library in my current C project. But my compiler is telling me

No such file or director #include <cstdint>

when used in my C project

main.c

#include "external.h"

int main()
{
    int a = myCppFunction(2000);

    return a;
}

I understand that this is because cstdint is a C++ standard library that I'm trying to use through my C file.

My questions are:


Solution

  • The c prefix in cstdint is because it's really a header file incorporated from C. The name in C is stdint.h.

    You need to conditionally include the correct header by detecting the __cplusplus macro. You also need this macro to use the extern "C" part, as that's C++ specific:

    #ifndef OUTPUT_FROM_CPP_H
    #define OUTPUT_FROM_CPP_H
    
    #ifdef __cplusplus
    // Building with a C++ compiler
    # include <cstdint>
    extern "C" {
    #else
    // Building with a C compiler
    # include <stdint.h>
    #endif
    
    uint8_t myCppFunction(uint8_t n);
    
    #ifdef __cplusplus
    }  // Match extern "C"
    #endif
    
    #endif