Mixing C and C++ in one file.

c c-plus-plus

I had to mix C and C++ because I was using a C library for something, and forgot the syntax. IsoCPP has the guide; the short answer is to declare C functions as extern "C".

Here’s a short MWE:

#include <stdio.h>
#include <execinfo.h>
#include <stdlib.h>
#include <iostream>
#include <string>

using namespace std;


extern "C" {
    void cfunction(char *arg) {
        printf("In C function, char argument %s\n", arg);
    }
}


int main(int argc, char **argv) {
 
    cfunction("test0");

}

Compile with g++ -g -std=c++11 mixccplusplus.cpp -o mixtest.

© Amy Tabb 2018 - 2023. All rights reserved. The contents of this site reflect my personal perspectives and not those of any other entity.