Advertisement

c++ -> c translator

Started by January 02, 2001 01:46 PM
1 comment, last by Adept 24 years ago
Hi I need a program that can translate any c++ source into pure c source. I know a program called CFront, but it is not free. I have to write a program to a platform that hasn''t c++ compiler... Can anyone help me ? Thanks, Adept
Well if you are just dealing with simple classes and such you could build a program that takes a C++ source file as an argument and ouputs a C source file with the equivalent class, but broken into structures and functions. For instance:

// A C++ class to break into a C structure with the C++
// methods broken into C functions that take a structure
// of this type as it''s argument.

class X {
public:
X(int iA, int iB) { iX = iA; iY = iB; }
void Print(void) { cout << iX << " " << iY << endl; }
int iX;
int iY;
};

/* Equivalent C source file */

typedef struct {
int iX;
int iY;
} X;

void InitX(X &xI, int iA, int iB) {
xI->iX = iA; xI->iX = iB;
}

void Print(X *xI) {
cout << xI->iX << " " << xI->iY << endl;
}

This is a completely working and equivalent example. The only problem lies within using private data and methods in the class. This shouldn''t be to hard to build either. Here is one way you could implement it:

Search for "class" string in file. Take name directly infront of the class and use it as the struct name. Now copy all contents between { after the name and }; and copy them into the structure. Rescan file and remove public: or private: indicators. Now scan again for methods. If constructors, deconstructors or copy constructors are specified build them first and append a void return type. Take their argument lists, but prefix it with a structure pointer to type X. Now apply this to the other methods and prefix a structure pointer to type X, and now you should have a working program that converts C++ classes to C structures. This is probably one of the major areas of difficulty in converting between C++ and C. You could next build a program to take cout statements and change them to printf.

Hope this helped,
William O''Brien
kernel@brunnet.net
"The time has come", the Walrus said, "To speak of many things."
Advertisement
Scoping would be really hard to do. C++ uses up to block-local scope, whereas C only lets you do function-local. You''d have to rename all of your variables like so:

C++ code:void func (){  int x; // one x  {    int x; // another x  }  {    int x; // yet a different x  }}C code:void func (){  int x, x_block_1, x_block_2;} 


Another real toughie would be virtual function tables that you''d have to implement directly. Hope you like function pointers.

Sounds like a really tough project. Good luck.

This topic is closed to new replies.

Advertisement