Skip to content

Instantly share code, notes, and snippets.

@amullins83
Created September 15, 2015 19:05
Show Gist options
  • Save amullins83/9853816d1609581db169 to your computer and use it in GitHub Desktop.
Save amullins83/9853816d1609581db169 to your computer and use it in GitHub Desktop.
Invoke C++ code within C

#Invoking C++ code within a C file

I don't know how useful this is in practice, but today I learned that you can invoke C++ code within a C library if needed. The basic process is to forward-declare C++ structs, then declare the function(s) to be invoked from the C library within an extern "C" block. The file containing these declarations will need to be included in the C source file and in the C++ header and source files. The C file can then be compiled normally with gcc and the C++ source with g++. Finally, the executable will need to be linked with g++ so that C++ operators and keywords will be defined.

This trivial example seems silly, but one can imagine a scenario where a C-library does useful work while taking a function pointer as an argument. The function declared in the extern "C" block here might be accepted as such an argument, and as long as the final result is linked with a C++ standard library, everything will work.

#!/bin/bash
gcc -o extern_new_main.o -c extern_new_main.c # This works!
g++ -o extern_new.o -c extern_new.cpp
g++ -o extern_new extern_new_main.o extern_new.o # This also works!
./extern_new # => DerivedClass object with address: 00464680
#include "extern_new.h"
extern "C" {
DerivedClass *create_derived_class(char a, char b) {
return new DerivedClass(a, b);
}
}
#ifndef EXTERN_NEW_H
#define EXTERN_NEW_H
#include "extern_new_function.h"
struct BaseClass {
public:
BaseClass(char a) : m_a(a) {}
void SetA(char a) { m_a = a; }
char GetA() { return m_a; }
private:
char m_a;
};
struct DerivedClass : public BaseClass {
public:
DerivedClass(char a, char b) : BaseClass(a), m_b(b) {}
void SetB(char b) { m_b = b; }
char GetB() { return m_b; }
private:
char m_b;
};
#endif
#ifndef EXTERN_NEW_FUNCTION_H
#define EXTERN_NEW_FUNCTION_H
#ifdef __cplusplus
extern "C" {
#endif
typedef struct DerivedClass DerivedClass;
DerivedClass *create_derived_class(char a, char b);
#ifdef __cplusplus
}
#endif
#endif
#include "extern_new_function.h"
#include <stdio.h>
int main() {
DerivedClass *derived = create_derived_class('a', 'b');
printf("DerivedClass object with address: %p\n", derived);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment