Just some random thoughts about automated conversion between C and C++ code.
Say, I have the following C code
typedef struct { int a; int b; } example_t; void example_set_a(example_t* example, int val) { example->a = val; } void example_set_b(example_t* example, int val) { example->b = val; } int example_get_sum(example_t* example) { return example->a + example->b};
The C++ equivalent would be
class cExample { private: int a; int b; public: void setA(int val); void setB(int val); int getSum(); }; void cExample::setA(int val) { a = val; } void cExample::setB(int val) { b = val; } int cExample::getSum() { return a + b; }
- Convert naming convention from snake_case to camelCase. Remote the _t suffix, add the c prefix.
- Place all members of the struct in the private part of the class.
- Take all functions that take a pointer to the struct, and place them in the pubic part of the class (removing the pointer to the struct)
This process feels rather mechanical, and it should be possible to automatically do the said conversion. The question is how?
Are there any existing tools for such tasks? This task doesn’t seem very unique to me, so I can imagine such tool to exist.
So far, I have found some website with an AI powered tool. While it performs the task, I would rather not use AI. I wish
for a tool that runs on my local machine.
If no such tool exists, how should I go around creating one. I need to parse the C code, up to the point where I can
identify the function signature, find where it begins and ends, find where the pointer to the struct is used and remove that part.
All things that should exist already. Think how syntax highlighting and refactoring tools in an IDE work. The parts to do
such tasks do exist. But what are these parts? Should I be looking into yacc or is that totally the wrong track?
“How to automate boilerplate code?”
Sometimes, the best answer seems to be, “use a modern language”. The difference between classic Java and Java with Lombok is perhaps instructive here, as a comparison.
Classic Java:
[code]public class Exmample {
private int a;
private int b;
public int setA(int a) { this.a = a; }
public int setB(int b) { this.b = b; }
public int getSum() { return a + b; }
}[/code]
With Lombok:
[code]import lombok.Setter;
@Setter
public class Exmample {
private int a;
private int b;
public int getSum() { return a + b; }
}[/code]
The full power of this library is quite a bit larger, but it automates a lot of what can be seen as ‘boring’. I would expect there could be certainly interest in the C/C++ world in something similar.
I’m an embedded engineer. I work with kibibytes of RAM and FLASH.
So far, I’ve been reluctant when it comes to even using C++ on a microcontroller.
In this perspective, C++ is the modern language 😉 I’m willing to give it a try, to see where it goes. But then, I’d like to write some driver, in both C and C++ variants. If I could write it once and transform the code to the right syntax.