简体   繁体   中英

Using (ugly) C code in C++ with extern “C”

I face some problems with ugly written old C code. I want to use a C++ compiler and use parts of this old code.

header.h

extern "C"{
int header();
}

header.c

#include "header.h"
int header(){
const int i=20;
int *ptr = &i;
}

This is compiling using gcc (4.9.3) with a warning (without the extern "C") but in g++ there is the error : "invalid conversion from 'const int*' to 'int*' [-fpermissive]"

I am not directly interested in this code but want to know if there is a way of getting any working C code compiling with a C++ compiler? (this is just an example what is "working" in C but not in C++ like the real problem is compiling with gcc but not with g++)

You have two alternatives:

  1. Fix all errors that are not valid C++, or
  2. Compile C files with gcc, and link them with C++ files

extern "C" only makes the C++ compiler to use C function names when it is calling the functions. If you choose to compile those functions with C++ compiler, it does not make those functions to actually compile with C rules.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM