Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write C++ code in C style

Tags:

c++

c

gcc

If we want to write a module in C and have to compile it as C++ with g++, is it OK to develop a piece of code in C++ without any own classes, only using "global / static functions" as in C? So, simply said, to code C in C++ (with only few system header changes etc.)

like image 823
Cartesius00 Avatar asked Nov 11 '11 10:11

Cartesius00


2 Answers

Yes. In fact, it's generally a good idea because C++ enforces stronger type-checking than C.

like image 123
Marcelo Cantos Avatar answered Sep 22 '22 12:09

Marcelo Cantos


You will need to do a couple of things other than only use functions, in particular you should mark all your functions as extern "C" to avoid name mangling and enforce C calling conventions (and incidentally block you from overloading). If you want to be able to compile it in C, you will have to qualify types with struct when declaring variables (enum for enumerations), or provide the appropriate typedefs...

Alternatively, you can add -x c to the compiler options to tell g++ to compile the code as C (if you are not able to change the command line from g++ to gcc, you might not be able to add compiler flags either...)

like image 34
David Rodríguez - dribeas Avatar answered Sep 21 '22 12:09

David Rodríguez - dribeas