Sort
Profile photo for Assistant
Assistant

Converting Octave code to C or C++ involves several steps, as Octave is primarily used for numerical computations with a syntax that is often more flexible than C/C++. Here’s a structured approach to help you with the conversion:

1. Understand the Code Logic

  • Before converting, ensure you fully understand what the Octave code does. Identify the algorithms, data structures, and flow of control.

2. Data Types

  • Octave uses dynamic typing, while C/C++ requires explicit data type declarations. Determine the appropriate C/C++ types for variables (e.g., double, int, float).

3. Array and Matrix Handling

  • Octav

Converting Octave code to C or C++ involves several steps, as Octave is primarily used for numerical computations with a syntax that is often more flexible than C/C++. Here’s a structured approach to help you with the conversion:

1. Understand the Code Logic

  • Before converting, ensure you fully understand what the Octave code does. Identify the algorithms, data structures, and flow of control.

2. Data Types

  • Octave uses dynamic typing, while C/C++ requires explicit data type declarations. Determine the appropriate C/C++ types for variables (e.g., double, int, float).

3. Array and Matrix Handling

  • Octave has built-in support for matrices and arrays. In C or C++, you need to either use arrays or a library like Eigen or Armadillo that provides matrix functionality.
  • Example:
  1. octave 
  2. A = [1, 2; 3, 4]; % Octave 

  • In C++ with Eigen:
  1. cpp 
  2. #include <Eigen/Dense> 
  3. Eigen::MatrixXd A(2, 2); 
  4. A << 1, 2, 3, 4; // C++ 

4. Functions and Syntax

  • Octave functions can often be converted directly into C/C++ functions, but you may need to change the syntax.
  • Example:
  1. octave 
  2. function y = myFunction(x) 
  3. y = x^2; 
  4. end 

  • In C++:
  1. cpp 
  2. double myFunction(double x) { 
  3. return x * x; 
  4. } 

5. Control Structures

  • Most control structures (if, for, while) are similar, but ensure to adjust the syntax to match C/C++.
  • Example:
  1. octave 
  2. for i = 1:10 
  3. disp(i); 
  4. end 

  • In C++:
  1. cpp 
  2. for (int i = 1; i <= 10; ++i) { 
  3. std::cout << i << std::endl; 
  4. } 

6. Libraries and Functions

  • Replace Octave functions with equivalent C/C++ standard library functions or appropriate third-party libraries. For example, use <cmath> for mathematical operations.

7. Memory Management

  • In C/C++, you have to manage memory manually using new and delete or utilize containers like std::vector which manage memory automatically.

8. Testing

  • After conversion, test the C/C++ code thoroughly to ensure that it produces the same results as the original Octave code.

Example Conversion

Here’s a simple example to illustrate the conversion process.

Octave Code:

  1. function y = computeSum(a, b) 
  2. y = a + b; 
  3. end 
  4.  
  5. result = computeSum(5, 7); 
  6. disp(result); 

C++ Code:

  1. #include <iostream> 
  2.  
  3. double computeSum(double a, double b) { 
  4. return a + b; 
  5. } 
  6.  
  7. int main() { 
  8. double result = computeSum(5, 7); 
  9. std::cout << result << std::endl; 
  10. return 0; 
  11. } 

Conclusion

Converting Octave code to C or C++ requires careful attention to detail, especially regarding data types and memory management. Libraries can help with matrix operations, and thorough testing is essential to ensure functionality matches the original code. If you have a specific piece of Octave code you’d like help with, feel free to share!

The Octave/MATLAB language is very different
from C and C++ in enough ways that it would be quite difficult to build a
tool to convert from Octave code to sensible, efficient, human-readable
C or C++. Fortunately, there are a couple of things that might work
that you can try before undertaking to rewrite your code:
First, try to compile Octave for your embedded platform. Even if this
doesn't work at first, it may simply be an issue with the build system
or an OS interaction feature that you might not need, so porting Octave
enough to fulfill your needs might not be unreasonable.
Second,

The Octave/MATLAB language is very different
from C and C++ in enough ways that it would be quite difficult to build a
tool to convert from Octave code to sensible, efficient, human-readable
C or C++. Fortunately, there are a couple of things that might work
that you can try before undertaking to rewrite your code:
First, try to compile Octave for your embedded platform. Even if this
doesn't work at first, it may simply be an issue with the build system
or an OS interaction feature that you might not need, so porting Octave
enough to fulfill your needs might not be unreasonable.
Second, look in to the Octave C++ integration features:

  • http://en.wikipedia.org/wiki/GNU_Octave#C++_Integration
  • http://wiki.octave.org/wiki.pl?CategoryExternal


If these methods don't work, you may want to look into the MATLAB
Compiler, which will let you compile MATLAB code into shared libraries.
Watch out, though, because this will be expensive, x86 only, unsupported
on an embedded OS, and you'll need to translate your code from Octave
to MATLAB (though there are tools that can help with that).

Where do I start?

I’m a huge financial nerd, and have spent an embarrassing amount of time talking to people about their money habits.

Here are the biggest mistakes people are making and how to fix them:

Not having a separate high interest savings account

Having a separate account allows you to see the results of all your hard work and keep your money separate so you're less tempted to spend it.

Plus with rates above 5.00%, the interest you can earn compared to most banks really adds up.

Here is a list of the top savings accounts available today. Deposit $5 before moving on because this is one of th

Where do I start?

I’m a huge financial nerd, and have spent an embarrassing amount of time talking to people about their money habits.

Here are the biggest mistakes people are making and how to fix them:

Not having a separate high interest savings account

Having a separate account allows you to see the results of all your hard work and keep your money separate so you're less tempted to spend it.

Plus with rates above 5.00%, the interest you can earn compared to most banks really adds up.

Here is a list of the top savings accounts available today. Deposit $5 before moving on because this is one of the biggest mistakes and easiest ones to fix.

Overpaying on car insurance

You’ve heard it a million times before, but the average American family still overspends by $417/year on car insurance.

If you’ve been with the same insurer for years, chances are you are one of them.

Pull up Coverage.com, a free site that will compare prices for you, answer the questions on the page, and it will show you how much you could be saving.

That’s it. You’ll likely be saving a bunch of money. Here’s a link to give it a try.

Consistently being in debt

If you’ve got $10K+ in debt (credit cards…medical bills…anything really) you could use a debt relief program and potentially reduce by over 20%.

Here’s how to see if you qualify:

Head over to this Debt Relief comparison website here, then simply answer the questions to see if you qualify.

It’s as simple as that. You’ll likely end up paying less than you owed before and you could be debt free in as little as 2 years.

Missing out on free money to invest

It’s no secret that millionaires love investing, but for the rest of us, it can seem out of reach.

Times have changed. There are a number of investing platforms that will give you a bonus to open an account and get started. All you have to do is open the account and invest at least $25, and you could get up to $1000 in bonus.

Pretty sweet deal right? Here is a link to some of the best options.

Having bad credit

A low credit score can come back to bite you in so many ways in the future.

From that next rental application to getting approved for any type of loan or credit card, if you have a bad history with credit, the good news is you can fix it.

Head over to BankRate.com and answer a few questions to see if you qualify. It only takes a few minutes and could save you from a major upset down the line.

How to get started

Hope this helps! Here are the links to get started:

Have a separate savings account
Stop overpaying for car insurance
Finally get out of debt
Start investing with a free bonus
Fix your credit

Profile photo for Leon Palafox

There is a way to write wrappers for matlab so they work in C and C++, it is called the Matlab Engine

http://www.mathworks.com/help/techdoc/matlab_external/f38569.html

Profile photo for Anumod Odungattu

There is a MATLAB toolbox called Coders toolbox which could do the job for you. But this is licensed toolbox and you need to purchase it if not available already.

Ublas tool as Ken mentioned is worth trying.
One could also use
Armadillo library in native C/C++ to achieve the same functionalities and can be tweaked for performance as well.

Profile photo for Ken Meltsner

There are at least 2 packages that can convert many Octave operations to C++:

Example Conversion of Matlab or Octave to C++ using Ublas


Page on octave-compiler.org (dead link)
Octave / Web%20*Home Live, but many links are dead -- probably hasn't been updated since 2005

The former appears to be alive -- the author has made some changes recently; the latter appears to be dead or moved. The toolkit underneath the second project is still available and actively maintained.

Boost your efficiency with refactorings, code analysis, unit test support, and an integrated debugger.
Profile photo for Dale Gulledge

While C++ isn’t a proper superset of C, the differences are so minor that they’re easy to deal with. So, your first step is to simply compile your C code with a C++ compiler. In that sense, the conversion is trivial.

You’ll need unit tests. It’s wonderful if the original code has them. Start by converting them from whatever C unit test framework was used to a C++ unit test framework. Do that without changing the code under test. If you don’t have unit tests with the original code, write them using a C++ unit test framework. You don’t need to convert any of the code under test to do that, except

While C++ isn’t a proper superset of C, the differences are so minor that they’re easy to deal with. So, your first step is to simply compile your C code with a C++ compiler. In that sense, the conversion is trivial.

You’ll need unit tests. It’s wonderful if the original code has them. Start by converting them from whatever C unit test framework was used to a C++ unit test framework. Do that without changing the code under test. If you don’t have unit tests with the original code, write them using a C++ unit test framework. You don’t need to convert any of the code under test to do that, except the trivial changes to make it compile with a C++ compiler.

However, you probably want to convert it in a more meaningful sense. One of the insights I got from reading Working Effectively With Legacy Code by Michael Feathers is that procedural code is object-oriented in a very crude sense. What he said is that the entire program is one big singleton object. In reality, if the code is reasonably modular, each subsystem can be treated as a singleton object.

So, you start by converting the code with that assumption. It’s worth getting a copy of his book, along with Refactoring To Patterns by Kerievsky and, of course Refactoring by Fowler. You’re going to be refactoring the code extensively. Even making each module into a class so that you can have a singleton object for each module has the potential to break things.

Once you’ve got all of the subsystems refactored into singleton objects, you can do additional refactoring. From there, it’s the kind of refactoring that is well documented for OO languages.

Profile photo for AlanM

I did this a couple of years ago for a couple hundred line C program. I figured that C++ is just a superset of C and that I could change the file extension from .c to .cpp. That it would compiler. Well not exactly. First thing I found is that this program had a lot of definitions that since it was written was now included in some Windows headers. Once I fixed that I found places where C++ required casts that C didn’t.

After a day or so I got the program to compile and run. The next step was to rewrite the program to use C++ so that it would be easier to understand and maintain.

My recommendation

I did this a couple of years ago for a couple hundred line C program. I figured that C++ is just a superset of C and that I could change the file extension from .c to .cpp. That it would compiler. Well not exactly. First thing I found is that this program had a lot of definitions that since it was written was now included in some Windows headers. Once I fixed that I found places where C++ required casts that C didn’t.

After a day or so I got the program to compile and run. The next step was to rewrite the program to use C++ so that it would be easier to understand and maintain.

My recommendation is to only convert that parts of the program to C++ that you need to maintain. Keep the rest of it in C and link them together into one program. In order to call a C function from C++ you have to declare it

extern “C”

Profile photo for Quora User

Here’s the thing: I wish I had known these money secrets sooner. They’ve helped so many people save hundreds, secure their family’s future, and grow their bank accounts—myself included.

And honestly? Putting them to use was way easier than I expected. I bet you can knock out at least three or four of these right now—yes, even from your phone.

Don’t wait like I did. Go ahead and start using these money secrets today!

1. Cancel Your Car Insurance

You might not even realize it, but your car insurance company is probably overcharging you. In fact, they’re kind of counting on you not noticing. Luckily,

Here’s the thing: I wish I had known these money secrets sooner. They’ve helped so many people save hundreds, secure their family’s future, and grow their bank accounts—myself included.

And honestly? Putting them to use was way easier than I expected. I bet you can knock out at least three or four of these right now—yes, even from your phone.

Don’t wait like I did. Go ahead and start using these money secrets today!

1. Cancel Your Car Insurance

You might not even realize it, but your car insurance company is probably overcharging you. In fact, they’re kind of counting on you not noticing. Luckily, this problem is easy to fix.

Don’t waste your time browsing insurance sites for a better deal. A company called Insurify shows you all your options at once — people who do this save up to $996 per year.

If you tell them a bit about yourself and your vehicle, they’ll send you personalized quotes so you can compare them and find the best one for you.

Tired of overpaying for car insurance? It takes just five minutes to compare your options with Insurify and see how much you could save on car insurance.

2. Ask This Company to Get a Big Chunk of Your Debt Forgiven

A company called National Debt Relief could convince your lenders to simply get rid of a big chunk of what you owe. No bankruptcy, no loans — you don’t even need to have good credit.

If you owe at least $10,000 in unsecured debt (credit card debt, personal loans, medical bills, etc.), National Debt Relief’s experts will build you a monthly payment plan. As your payments add up, they negotiate with your creditors to reduce the amount you owe. You then pay off the rest in a lump sum.

On average, you could become debt-free within 24 to 48 months. It takes less than a minute to sign up and see how much debt you could get rid of.

3. You Can Become a Real Estate Investor for as Little as $10

Take a look at some of the world’s wealthiest people. What do they have in common? Many invest in large private real estate deals. And here’s the thing: There’s no reason you can’t, too — for as little as $10.

An investment called the Fundrise Flagship Fund lets you get started in the world of real estate by giving you access to a low-cost, diversified portfolio of private real estate. The best part? You don’t have to be the landlord. The Flagship Fund does all the heavy lifting.

With an initial investment as low as $10, your money will be invested in the Fund, which already owns more than $1 billion worth of real estate around the country, from apartment complexes to the thriving housing rental market to larger last-mile e-commerce logistics centers.

Want to invest more? Many investors choose to invest $1,000 or more. This is a Fund that can fit any type of investor’s needs. Once invested, you can track your performance from your phone and watch as properties are acquired, improved, and operated. As properties generate cash flow, you could earn money through quarterly dividend payments. And over time, you could earn money off the potential appreciation of the properties.

So if you want to get started in the world of real-estate investing, it takes just a few minutes to sign up and create an account with the Fundrise Flagship Fund.

This is a paid advertisement. Carefully consider the investment objectives, risks, charges and expenses of the Fundrise Real Estate Fund before investing. This and other information can be found in the Fund’s prospectus. Read them carefully before investing.

4. Earn Up to $50 this Month By Answering Survey Questions About the News — It’s Anonymous

The news is a heated subject these days. It’s hard not to have an opinion on it.

Good news: A website called YouGov will pay you up to $50 or more this month just to answer survey questions about politics, the economy, and other hot news topics.

Plus, it’s totally anonymous, so no one will judge you for that hot take.

When you take a quick survey (some are less than three minutes), you’ll earn points you can exchange for up to $50 in cash or gift cards to places like Walmart and Amazon. Plus, Penny Hoarder readers will get an extra 500 points for registering and another 1,000 points after completing their first survey.

It takes just a few minutes to sign up and take your first survey, and you’ll receive your points immediately.

5. Get Up to $300 Just for Setting Up Direct Deposit With This Account

If you bank at a traditional brick-and-mortar bank, your money probably isn’t growing much (c’mon, 0.40% is basically nothing).

But there’s good news: With SoFi Checking and Savings (member FDIC), you stand to gain up to a hefty 3.80% APY on savings when you set up a direct deposit or have $5,000 or more in Qualifying Deposits and 0.50% APY on checking balances — savings APY is 10 times more than the national average.

Right now, a direct deposit of at least $1K not only sets you up for higher returns but also brings you closer to earning up to a $300 welcome bonus (terms apply).

You can easily deposit checks via your phone’s camera, transfer funds, and get customer service via chat or phone call. There are no account fees, no monthly fees and no overdraft fees. And your money is FDIC insured (up to $3M of additional FDIC insurance through the SoFi Insured Deposit Program).

It’s quick and easy to open an account with SoFi Checking and Savings (member FDIC) and watch your money grow faster than ever.

Read Disclaimer

5. Stop Paying Your Credit Card Company

If you have credit card debt, you know. The anxiety, the interest rates, the fear you’re never going to escape… but a website called AmONE wants to help.

If you owe your credit card companies $100,000 or less, AmONE will match you with a low-interest loan you can use to pay off every single one of your balances.

The benefit? You’ll be left with one bill to pay each month. And because personal loans have lower interest rates (AmONE rates start at 6.40% APR), you’ll get out of debt that much faster.

It takes less than a minute and just 10 questions to see what loans you qualify for.

6. Lock In Affordable Term Life Insurance in Minutes.

Let’s be honest—life insurance probably isn’t on your list of fun things to research. But locking in a policy now could mean huge peace of mind for your family down the road. And getting covered is actually a lot easier than you might think.

With Best Money’s term life insurance marketplace, you can compare top-rated policies in minutes and find coverage that works for you. No long phone calls. No confusing paperwork. Just straightforward quotes, starting at just $7 a month, from trusted providers so you can make an informed decision.

The best part? You’re in control. Answer a few quick questions, see your options, get coverage up to $3 million, and choose the coverage that fits your life and budget—on your terms.

You already protect your car, your home, even your phone. Why not make sure your family’s financial future is covered, too? Compare term life insurance rates with Best Money today and find a policy that fits.

Profile photo for Quora User

You need to hire a programmer who will write your code again in C++.

My advice: DON'T!

Such questions comes from people expecting some magic tricks which would turn their code in one language to another. Unless you have real reason to, it doesn't make sense to turn working code upside down by complete rewrite. If you want to use C++ in your project it's better to successively add it into your codebase for new features, but you need good experienced C++ programmers.

Profile photo for Tony Flury

carefully - there isn’t a tool to do it.

personally I would start with the unit testing - either find a way that the unit tests for the python code can be re-used simply to test the C++ code (this isn’t always easy) or rewrite your Python unit-tests into C++; a framework like catch might be a good choice.

I would then start by picking a single simple class or function in Python and rewriting it in C++ = remember that the C++ standard library has Hashmaps, sets and vectors which can be used in many cases as replacements for Python builtins.

I would go function by function and class by class - and

carefully - there isn’t a tool to do it.

personally I would start with the unit testing - either find a way that the unit tests for the python code can be re-used simply to test the C++ code (this isn’t always easy) or rewrite your Python unit-tests into C++; a framework like catch might be a good choice.

I would then start by picking a single simple class or function in Python and rewriting it in C++ = remember that the C++ standard library has Hashmaps, sets and vectors which can be used in many cases as replacements for Python builtins.

I would go function by function and class by class - and eventually all of your test cases will pass.

Profile photo for Metis Chan

With today’s modern day tools there can be an overwhelming amount of tools to choose from to build your own website. It’s important to keep in mind these considerations when deciding on which is the right fit for you including ease of use, SEO controls, high performance hosting, flexible content management tools and scalability. Webflow allows you to build with the power of code — without writing any.

You can take control of HTML5, CSS3, and JavaScript in a completely visual canvas — and let Webflow translate your design into clean, semantic code that’s ready to publish to the web, or hand off

With today’s modern day tools there can be an overwhelming amount of tools to choose from to build your own website. It’s important to keep in mind these considerations when deciding on which is the right fit for you including ease of use, SEO controls, high performance hosting, flexible content management tools and scalability. Webflow allows you to build with the power of code — without writing any.

You can take control of HTML5, CSS3, and JavaScript in a completely visual canvas — and let Webflow translate your design into clean, semantic code that’s ready to publish to the web, or hand off to developers.

If you prefer more customization you can also expand the power of Webflow by adding custom code on the page, in the <head>, or before the </head> of any page.

Get started for free today!

Trusted by over 60,000+ freelancers and agencies, explore Webflow features including:

  • Designer: The power of CSS, HTML, and Javascript in a visual canvas.
  • CMS: Define your own content structure, and design with real data.
  • Interactions: Build websites interactions and animations visually.
  • SEO: Optimize your website with controls, hosting and flexible tools.
  • Hosting: Set up lightning-fast managed hosting in just a few clicks.
  • Grid: Build smart, responsive, CSS grid-powered layouts in Webflow visually.

Discover why our global customers love and use Webflow | Create a custom website.

Profile photo for Jerry Coffin

That depends on what sort of code you start with, and what sort of result you want.

If you're starting with K&R code, and just want the code to become acceptable to a C++ compiler, you need to do a couple of things.

1. Declare all functions (with parameter types).
2. Use ANSI definitions for all functions.

In K&R C, a function declaration looks something like: int f();. It says that `f` is a function returning an int, but says nothing about the number or type of parameters it accepts. C++ demands a function declaration similar to an ANSI C function prototype, such as: int f(int, long);, which say

That depends on what sort of code you start with, and what sort of result you want.

If you're starting with K&R code, and just want the code to become acceptable to a C++ compiler, you need to do a couple of things.

1. Declare all functions (with parameter types).
2. Use ANSI definitions for all functions.

In K&R C, a function declaration looks something like: int f();. It says that `f` is a function returning an int, but says nothing about the number or type of parameters it accepts. C++ demands a function declaration similar to an ANSI C function prototype, such as: int f(int, long);, which says `f` takes two parameters of type `int` and `long` respectively.

In K&R C, a function definition could look something like this:

  1. int f(x, y) 
  2. int x; 
  3. long y; 
  4. { 
  5. // ... body here 
  6. } 

C++ demands the "new" style of definition like this:

  1. int f(int x, long y)  
  2. {  
  3. // body here 
  4. } 

Back in the early '90s there were a few tools available to do this sort of conversion automatically. The one I recall was named "cproto".

I don't know of any that even attempted to create meaningful class structures, or anything like that though. Nor do I know of any that attempted to automate a few things you might have to rename, such as if you'd used a variable named "class" or a function named "delete". Most of these are just handled with an editor if they arise.

Profile photo for Greg Kemnitz

Yes, the C compiler, the C++ compiler - and you :)

If you want C code to compile in a C++ compiler, you should first start by converting the C code to strict ANSI compliance by enabling the --ansi --pedantic --Wall options in gcc or the equivalent options in your compiler.

After you've done this and run a full regression test on your code to confirm that it still works - it's easy to introduce bugs doing these sorts of conversions - you can try to see how far you get by compiling with a C++ compiler.

There are enough differences that this may not be trivial even after ANSI-izing: Compatibility of

Yes, the C compiler, the C++ compiler - and you :)

If you want C code to compile in a C++ compiler, you should first start by converting the C code to strict ANSI compliance by enabling the --ansi --pedantic --Wall options in gcc or the equivalent options in your compiler.

After you've done this and run a full regression test on your code to confirm that it still works - it's easy to introduce bugs doing these sorts of conversions - you can try to see how far you get by compiling with a C++ compiler.

There are enough differences that this may not be trivial even after ANSI-izing: Compatibility of C and C++ - particularly for "system"-style code that does a lot of cleverness with casts that C++ doesn't like.

After this is done, you have C code that builds with a C++ compiler. You now need to re-run your full regression test suite on this second pass, and you're done. Naturally, you don't have fancy OO code yet...

That said, a big question is why? If you have a C library you want to call from C++, you can use extern "C" to allow your C++ to call your C and vice versa (for C-compatible entry points into C++) - and not go through a potentially laborious and bug-inducing conversion process.

Profile photo for Sqandr Sqandarni

I’m guessing you are looking for a solution that is free and so the existing and correct answer, buying MATLab® Coder, is not an option.

I’m currently playing with an open source package from the University of Washington:

Example Conversion of Matlab or Octave to C++ using Ublas

EDIT —

that package isn’t helpful, the name is not that accurate.

The following might be a better bet:

https://github.com/jonathf/matlab2cpp/blob/master/manual.pdf

Profile photo for Kirby Urner

You can go the other direction: write C++ in such a way that Python can import it and use it. That’s what they do over at Google I’m told. Use Python as an API to C++ and you’re golden.

There’s also Cython, a language very like Python, as close as possible, that outputs in C source and assembler.

If there were any generic solution to the Python-to-C++ challenge, then Python would be a com...

Profile photo for Karl Smith-Petersen

The string would have to contain a complete C program and would need to be error free (no syntax or linking errors) in order to be saved to a file and run through the compile/link procedure before being executed (noted in another answer). I imagine it would be executed as a separate thread or spawned process.

Interestingly, a feature of the newest version of the MS C/C++development environment back in ’98 (released after I left MS) included the “edit and continue” feature which basically accomplished what you are asking about… sort of.

It allowed you to modify the code as it was running (from th

The string would have to contain a complete C program and would need to be error free (no syntax or linking errors) in order to be saved to a file and run through the compile/link procedure before being executed (noted in another answer). I imagine it would be executed as a separate thread or spawned process.

Interestingly, a feature of the newest version of the MS C/C++development environment back in ’98 (released after I left MS) included the “edit and continue” feature which basically accomplished what you are asking about… sort of.

It allowed you to modify the code as it was running (from the debugger) and have that new code linked dynamically into the currently running process so you could continue the existing process using the new code. It was a truly amazing feature which required the brainpower of the dev lead for the linker to imagine and write.

As I recall, it would take the entire function being edited, recompile it into a separate DLL and modify the link table of the current process to call the function in the new DLL rather than the original version. Please don’t hold me to that loose description as I was not intimately engaged in the actual development of the feature, but I believe that was the gist of how it was accomplished.

Obviously, there were limitations as to the scope of the edits being made at any one time, and I’m not sure you could edit the main program body. Nonetheless, it was a brilliant bit of work by the most adept developer I ever met and had the pleasure to work with.

Profile photo for Khan Sadh Mostafa

Roughly speaking, C is a subset of C++.

If we go very deep into technical spec, C is not exact subset of C++. Many C code can effortlessly be compiled as C++ code, most other can be glued in easily. See

Loïc Mercier [ https://www.quora.com/profile/Loïc-Mercier ]

's answer and also read answers at

Can we compile a C code in a C++ compiler? [ https://www.quora.com/Can-we-compile-a-C-code-i...

Profile photo for Abhinav Muralidhar Gurram

You can use the MATLAB Compiler SDK toolbox, which helps create C++ shared libraries from MATLAB code. These libraries can then be integrated with other C++ projects or a C++ driver program can be used to implement this shared library.

Hope this helps!

Profile photo for Martin Jansche

If you only use features from before Java 1.5, you can use JCGO to translate Java source to C.

You can always decide to rewrite your project. I would target modern C++ though, which is a much closer match to Java than C is. If your project is large and you don't want to wait until your entire rewrite is finished, you may need to either do an inside-out replacement where you rewrite the innermost code in C++ first and call from the outer Java program via JNI. Or break it up into loosely coupled services and rewrite each service in C++. Either way you can make incremental progress without having

If you only use features from before Java 1.5, you can use JCGO to translate Java source to C.

You can always decide to rewrite your project. I would target modern C++ though, which is a much closer match to Java than C is. If your project is large and you don't want to wait until your entire rewrite is finished, you may need to either do an inside-out replacement where you rewrite the innermost code in C++ first and call from the outer Java program via JNI. Or break it up into loosely coupled services and rewrite each service in C++. Either way you can make incremental progress without having to wait for the full rewrite to finish first.

Profile photo for Quora User

You don’t? At least… Not without a large amount of support code in various libraries that already exist in any number of G-Code interpreters that actually interpret the code for the various machines that use it.

G-Code is a hardware control language and not a general programming language. It’s more akin to the graphics language Logo or the drawing control language of the classic “Windows Metafile”. Its commands are things like “change x-axis position by 0.10mm positive” or “set spindle speed to 300 RPM” — just like Logo has “pen up”, “pen down” and all the other commands for telling the “turtle

You don’t? At least… Not without a large amount of support code in various libraries that already exist in any number of G-Code interpreters that actually interpret the code for the various machines that use it.

G-Code is a hardware control language and not a general programming language. It’s more akin to the graphics language Logo or the drawing control language of the classic “Windows Metafile”. Its commands are things like “change x-axis position by 0.10mm positive” or “set spindle speed to 300 RPM” — just like Logo has “pen up”, “pen down” and all the other commands for telling the “turtle” where to go.

Profile photo for Chris Long

What do you mean by ‘Arduino code’?

The default language that pretty much everyone uses to program Arduinos is C++. If you write a simple program for an Arduino, without using any C++ specific language features, then the code you’ve written will probably compile as C by any C compiler.

But then you’d also need that compiler to supports the Arduino libraries and emits the proper ATmega or ARM machine code, etc, so I don’t know why you’d do that.

If you’re just a bit put off by the thought of having to write C++ code to work with your Arduino - don’t be. You don’t need to know any special C++ featu

What do you mean by ‘Arduino code’?

The default language that pretty much everyone uses to program Arduinos is C++. If you write a simple program for an Arduino, without using any C++ specific language features, then the code you’ve written will probably compile as C by any C compiler.

But then you’d also need that compiler to supports the Arduino libraries and emits the proper ATmega or ARM machine code, etc, so I don’t know why you’d do that.

If you’re just a bit put off by the thought of having to write C++ code to work with your Arduino - don’t be. You don’t need to know any special C++ features to write simple Arduino programs.

Profile photo for Lorenzo Snow

Actually, you can’t. In reality I mean. Of course, if you’re genius, and you’ll write your own converter, with preprocessor, parser, memory-manager, test-system, decompiler, debug-injector, etc, you’ll can convert it. But, it’s a mess, you shouldn’t do this. If your project about 500k SLOC, you should maintain it in java your whole life, if it less than 30k SLOC, just rewrite it, with unit-tests. You can’t trust any project, which was converted automatically from one language to another. It’s unprofessional, there’s no machine/program, which can do it properly. Of course, any company may sold

Actually, you can’t. In reality I mean. Of course, if you’re genius, and you’ll write your own converter, with preprocessor, parser, memory-manager, test-system, decompiler, debug-injector, etc, you’ll can convert it. But, it’s a mess, you shouldn’t do this. If your project about 500k SLOC, you should maintain it in java your whole life, if it less than 30k SLOC, just rewrite it, with unit-tests. You can’t trust any project, which was converted automatically from one language to another. It’s unprofessional, there’s no machine/program, which can do it properly. Of course, any company may sold you solution. But, how will you maintain that unreadable mess in the future? Did you see translated programs before? I can give you an example: Nim language, you write your code on pretty language, called Nim, it looks like python in two words, then, translator is converting your source code from Nim to C, and it looks like tons of variables like _10000987garatehj_90__finder__wrap__xx_0, do you want this as a result? I don’t think so. Because, all what you’ll get as a result - you’ll rewrite your project by yourself, and spend your time twice.

Profile photo for Michael Bauers

Technically, the C++ code IS the software. If you mean how do you get an executable image, for UNIX or Windows, you need a compiler.

For simple C++ programming, there’s a number of “obvious” options.

  1. Windows - Use Visual Studio Community Edition. That’s what I use at home. You will want to create a project who’s type is “Console App”. It’s a pain to sort through all the project types, and Visual Studio has a learning curve. But once you learn it, you can do a lot with it. I routinely write sample code for Quora questions using this approach.
  2. Windows - Install Windows Subsystem for Linux. Use g++

Technically, the C++ code IS the software. If you mean how do you get an executable image, for UNIX or Windows, you need a compiler.

For simple C++ programming, there’s a number of “obvious” options.

  1. Windows - Use Visual Studio Community Edition. That’s what I use at home. You will want to create a project who’s type is “Console App”. It’s a pain to sort through all the project types, and Visual Studio has a learning curve. But once you learn it, you can do a lot with it. I routinely write sample code for Quora questions using this approach.
  2. Windows - Install Windows Subsystem for Linux. Use g++ to compile ( possibly with option -std=c++11, if needed.) You can edit in windows. I use Sublime. This is how I develop C++ at work. Downside is mainly installing the subsystem, and learning some Linux commands if you don’t know Linux. Software development is like that. If you want easy, use Python.
  3. Linux - Use g++. Make sure like mentioned above, C++11 is enabled. Edit with vi or emacs. I only use this option when forced to do it. I have used vi since the 1980s. Can’t say I find it easier than using Sublime for editing.

Good luck!

There’s many other options. Just giving you the ones I use.

Profile photo for Alexander Lehmann

Most of C code will compile with C++, if it doesn’t you can keep it as C and interface it with your C++ code using the extern C calling conventions.

It depends on what you want to do, most of the time a C program will work with only minor changes, but you end up with C code that is not really following C++ concepts, so you will not have much benefit from porting it.

Profile photo for Chris Reid

You are in luck, because the same compiler is used for both languages.

It will be simpler if you do not include any C++ libraries in your code, including the STL headers. Only use the <c…> headers.

That is probably not what you are trying to do, however.

What is usually done for this is to write external C wrapper functions for the c++ calls, and translate the data members to C structures.

Say we had a Point Vector C++ struct that we wanted to use in a C program.

  1. // Pvector.cpp 
  2. #include <vector> 
  3. #include <algorithm> 
  4.  
  5. struct Point 
  6. { 
  7. int x, y; 
  8.  
  9. Point add(const Point& p) 
  10. { 
  11. return Point{ x + p.x , y 

You are in luck, because the same compiler is used for both languages.

It will be simpler if you do not include any C++ libraries in your code, including the STL headers. Only use the <c…> headers.

That is probably not what you are trying to do, however.

What is usually done for this is to write external C wrapper functions for the c++ calls, and translate the data members to C structures.

Say we had a Point Vector C++ struct that we wanted to use in a C program.

  1. // Pvector.cpp 
  2. #include <vector> 
  3. #include <algorithm> 
  4.  
  5. struct Point 
  6. { 
  7. int x, y; 
  8.  
  9. Point add(const Point& p) 
  10. { 
  11. return Point{ x + p.x , y + p.y };  
  12. } 
  13.  
  14. Point subt(const Point& p) 
  15. { 
  16. return Point{ x - p.x , y - p.y};  
  17. } 
  18.  
  19. }; 
  20.  
  21.  
  22. Point* copy_array( Point* a, Point* b, size_t n) 
  23. { 
  24.  
  25. Point* ap = a; 
  26. Point* bp = b; 
  27. Point* end = a+n; 
  28.  
  29. while( ap < end) *(bp++) = *(ap++); 
  30.  
  31. return b; 
  32. } 
  33.  
  34.  
  35. std::vector<Point> make_PointVector(const Point* parray, size_t n) 
  36. { 
  37. std::vector<Point> pvec; 
  38.  
  39. pvec.reserve(n); 
  40.  
  41. std::copy_n( parray, n, pvec.begin() );  
  42.  
  43. return pvec; 
  44. } 

OK we can compile it to a binary object file:

  1. g++ -c Pvector.cpp 

to obtain Pvector.o, which defines a Point struct and two C++ functions, one to make a vector of Points, another to copy point arrays.

We create an interface file “pv_interface.cpp, with some helper functions and designate that the function will have C linking conventions, so that their names will not get mangled the way C++ normally does it.

  1. // pv_interface.cpp 
  2.  
  3. #include <cstddef> 
  4. #include <cstdint> 
  5. #include "Pvector.cpp" 
  6.  
  7. extern "C" { // C linking  
  8.  
  9. Point* copy_point_array(Point* a, Point* b, size_t n) 
  10. { 
  11. return copy_array(a, b, n); 
  12. } 
  13.  
  14.  
  15. Point* new_point_vector(Point* parray, size_t n) 
  16. { 
  17. return make_PointVector(parray, n).data(); 
  18. } 
  19. } // extern "C" 

Compile it:

  1. g++ -c pv_interface.cpp  

to pv_interface.o.

Now we integrate it into out C driver

  1. /* main.c */ 
  2. #include <stdio.h> 
  3.  
  4. /* declare C struct type with same members */ 
  5. typedef struct {int x, y; } Point; 
  6.  
  7. /* function prototypes from pv_interface */ 
  8. Point* copy_point_array(Point* a, Point* b, size_t n); 
  9. Point* new_point_vector(Point* parray, size_t n); 
  10.  
  11.  
  12. int main(int argc, char** argv) 
  13. { 
  14.  
  15. Point* parray = new_point_vector(parray, 10); 
  16.  
  17. for(int i = 0; i < 10; i++) 
  18. { 
  19. Point tmp = (Point){ i, 3*i}; 
  20. parray[i] = tmp; 
  21. fprintf(stdout, "%d :\t { %d , %d} \n" , i, tmp.x, tmp.y); 
  22. } 
  23.  
  24.  
  25. return 0; 
  26. } 

We provide a definition of Point struct matching the actual data members of the C++ class. We provide function prototypes (signatures) for the interface we have built.

We then compile it with the object files and the standard c++ shared library.

  1. gcc -o pv main.c pv_interface.o -lstdc++  

Realize that pvinterface.o includes Pvector.cpp in it, so has the code for Point and its utilities compiled in, and you cannot call any STL without adding in the shared library which contains just about all of the C++ code you need.

try it:

  1. /pv 
  2. 0 : { 0 , 0}  
  3. 1 : { 1 , 3}  
  4. 2 : { 2 , 6}  
  5. 3 : { 3 , 9}  
  6. 4 : { 4 , 12}  
  7. 5 : { 5 , 15}  
  8. 6 : { 6 , 18}  
  9. 7 : { 7 , 21}  
  10. 8 : { 8 , 24}  
  11. 9 : { 9 , 27} 

Check it for leaks and such:

  1. valgrind ./pv 
  2.  
  3. /** A bunch of MACRO CRAP .... */ 
  4.  
  5. 0 : { 0 , 0}  
  6. 1 : { 1 , 3}  
  7. 2 : { 2 , 6}  
  8. 3 : { 3 , 9}  
  9. 4 : { 4 , 12}  
  10. 5 : { 5 , 15}  
  11. 6 : { 6 , 18}  
  12. 7 : { 7 , 21}  
  13. 8 : { 8 , 24}  
  14. 9 : { 9 , 27}  
  15. ... 
  16.  
  17. ==1371240==  
  18. ==1371240== HEAP SUMMARY: 
  19. ==1371240== in use at exit: 0 bytes in 0 blocks 
  20. ==1371240== total heap usage: 3 allocs, 3 frees, 73,808 bytes allocated 
  21. ==1371240==  
  22. ==1371240== All heap blocks were freed -- no leaks are possible 

Valgrind says all allocations are recovered, so you can be confident that
the interface is valid on first analysis.

Summary:

Provide a C interface to your C++ code that hides the C++ only stuff, and provides a C linkage to its own interface. Make object files that provide the code without forcing the C compiler to try to make sense of C++ source code.

Provide a C interface declaration (in a .h file, or in the C file compiled (main.c) that tells the C compiler the composition of the struct data, types translated to C syntax, and the function prototypes.

Compiler together with the objects and C++ standard shared library linked in.

The main problem is making sure that things in C are not double defined, specifically function implementations.

An additional note is that notice that the main.c creates Point structure tmp and assigns it values, then uses the pointer to the array in the vector as if it was a C array. The vector destructs when it goes out of scope, automatically.

Such integration is often a lot more hairy and you need to create more interface functions. A good knowledge of C and C++ and pointers and so on is essential, and this stuff is usually a forced decision because there is no other choice. But C and C++ are fast as fast gets generally so you can get away with layers of wrapping an never notice the overhead or speed of extra calls at runtime.

Profile photo for Muhammad Junaid Iqbal

In your virtualenv, install SeaSnake, and then run it, passing in the name of a C++ source file (or files, if you want to provide the header as well as the cpp file):

$ pip install seasnake

$ seasnake -s path/to/MyClass.cpp

This will output a MyClass.py Python module to the console.

If your code requires external include files or definitions, you can use the -D and -I options.

>>>>>>>

Once you get started coding in Python ... and get some feel for its (often very) simple coding style and power ... you may then want to DO many of your programming jobs in Python first ... and many of those, then ... m

In your virtualenv, install SeaSnake, and then run it, passing in the name of a C++ source file (or files, if you want to provide the header as well as the cpp file):

$ pip install seasnake

$ seasnake -s path/to/MyClass.cpp

This will output a MyClass.py Python module to the console.

If your code requires external include files or definitions, you can use the -D and -I options.

>>>>>>>

Once you get started coding in Python ... and get some feel for its (often very) simple coding style and power ... you may then want to DO many of your programming jobs in Python first ... and many of those, then ... may never get recoded in C++ :)

Here is a little demo C++

struct 'Contact' ...

with a way one might recode it in Python 3

that may help get you past 'go' ...

Firstly the C++ code ...

// Cpp_vs_Python.cpp //

#include <iostream>

#include <string>

using namespace std;

struct Contact

{

string name;

string phone;

string toString() const

{

return name + ", " + phone;

}

} ;

typedef Contact* iter;

int main()

{

Contact book[] = { {"Sam", "1234567890"},

{"Bill", "2345678901"} };

iter it,

begin = book,

end = book + (sizeof book / sizeof *book) ;

cout << "Showing contacts in book ...\n";

for( it = begin; it != end; ++it )

cout << it->toString() << endl;

cout << "Press 'Enter' to continue/exit ... " << flush;

string dummy;

getline( cin, dummy );

}

Ok ... now here is how one might recode this in Python 3
(Note how much shorter and simpler is the Python code.)

# Cpp_vs_Python.py #

class Contact:

def __init__(self, name, phone):

self.name = name

self.phone = phone

def __str__(self):

return self.name + ', ' + self.phone

# get some data into a book (a list of Contact)

book = [ Contact("Sam", "1234567890"), Contact("Bill", "2345678901") ]

#show the book

print( 'Showing contacts in book ...' )

for item in book:

print( item )

input( "Press 'Enter' to continue/exit ... "

Profile photo for Reza Alavi
Profile photo for Akash Telote

If you are trying to use as a part of your program, you can use atoi function to convert string to an integer. You will require to include cstdlib library in your program.

For eg.,

// C++ program to use atoi to convert string to integer

#include <iostream>

#include <cstdlib>

using namespace std;

int main()

{

const char *str1 = "56";

const char *str2 = "5.59";

const char *str3 = "3745 geek";

int num1 = atoi(str1);

int num2 = atoi(str2);

int num3 = atoi(str3);

cout << "atoi of (\"" << str1

<< "\") is " << num1 << '\n';

cout << "atoi of (\"" << str2

<< "\") is " << num2 << '\n';

cout << "atoi of (\"" << str3

<< "\"

If you are trying to use as a part of your program, you can use atoi function to convert string to an integer. You will require to include cstdlib library in your program.

For eg.,

// C++ program to use atoi to convert string to integer

#include <iostream>

#include <cstdlib>

using namespace std;

int main()

{

const char *str1 = "56";

const char *str2 = "5.59";

const char *str3 = "3745 geek";

int num1 = atoi(str1);

int num2 = atoi(str2);

int num3 = atoi(str3);

cout << "atoi of (\"" << str1

<< "\") is " << num1 << '\n';

cout << "atoi of (\"" << str2

<< "\") is " << num2 << '\n';

cout << "atoi of (\"" << str3

<< "\") is " << num3 << '\n';

return 0;

}

And if you want to implement the functionality of string to an integer then:

// C function to implement atoi functionality

#include <stdio.h>

int toString(char a[]) {

int c, sign, offset, n;

if (a[0] == '-') { // Handle negative integers

sign = -1;

}

if (sign == -1) { // Set starting position to convert

offset = 1;

}

else {

offset = 0;

}

n = 0;

for (c = offset; a[c] != '\0'; c++) {

n = n * 10 + a[c] - '0';

}

if (sign == -1) {

n = -n;

}

return n;

}

int main()

{

char a[20];

int n;

printf("Input a string to convert to an integer\n");

scanf("%s", a);

n = toString(a);

printf("String = %s\nInteger = %d\n", a, n);

return 0;

}

Profile photo for Quora User

The languages are different and should be treated as different. Especially with the latest year additions to the C++ language.

You can do #extern ”C”{…}

and then compile your C code separately with a C compiler from the same vendor and link together into your C++ program.

Profile photo for Benji Lampel

You seem to have some sort of misconception here, but the short answer is that C code is used to explain an algorithm to a machine.

Your question is a little backwards; you actually want to convert algorithms from a series of steps in natural language into C code. If you’re converting C code to an algorithm, what you’re really doing is describing the algorithm in a natural language instead of a computer language.

To “convert” C code into an algorithm, then, all you have to do is look at the C code and write down what each line or block is doing. Going the other way, you take statements written i

You seem to have some sort of misconception here, but the short answer is that C code is used to explain an algorithm to a machine.

Your question is a little backwards; you actually want to convert algorithms from a series of steps in natural language into C code. If you’re converting C code to an algorithm, what you’re really doing is describing the algorithm in a natural language instead of a computer language.

To “convert” C code into an algorithm, then, all you have to do is look at the C code and write down what each line or block is doing. Going the other way, you take statements written in a natural language and implement them in code (more common); generally the C code will take more space and time to write out because of explicit variable declarations and memory management that don’t come up the same way in natural language.

Profile photo for Jesse Glover

original question:

Can anyone help me convert Python code to C or C++?

answer:

Not very likely, however, it isn’t very difficult to do some quick research to learn what the variable declarations are and attribute them to the C/ C++ equivalent.

  1. #!/usr/bin/env python 
  2. #original Boyer-Moore implementor (v1): Shriphani Palakodety 
  3.  
  4. import time 
  5.  
  6. bcs = {} #the table 
  7.  
  8. def goodSuffixShift(key): 
  9. for i in xrange(len(key)-1, -1, -1): 
  10. if key[i] not in bcs.keys(): 
  11. bcs[key[i]] = len(key)-i-1 
  12.  
  13.  
  14. #---------------------- v1 ---------------------- 
  15. def searchv1(text, key): 
  16. #base from Shriphani Palakodety fixed for 

original question:

Can anyone help me convert Python code to C or C++?

answer:

Not very likely, however, it isn’t very difficult to do some quick research to learn what the variable declarations are and attribute them to the C/ C++ equivalent.

  1. #!/usr/bin/env python 
  2. #original Boyer-Moore implementor (v1): Shriphani Palakodety 
  3.  
  4. import time 
  5.  
  6. bcs = {} #the table 
  7.  
  8. def goodSuffixShift(key): 
  9. for i in xrange(len(key)-1, -1, -1): 
  10. if key[i] not in bcs.keys(): 
  11. bcs[key[i]] = len(key)-i-1 
  12.  
  13.  
  14. #---------------------- v1 ---------------------- 
  15. def searchv1(text, key): 
  16. #base from Shriphani Palakodety fixed for single char 
  17. i = len(key)-1 
  18. index = len(key) -1 
  19. j = i  
  20.  
  21. while True: 
  22. if i < 0: 
  23. return j + 1 
  24. elif j > len(text): 
  25. return "not found" 
  26. elif text[j] != key[i] and text[j] not in bcs.keys(): 
  27. j += len(key) 
  28. i = index 
  29. elif text[j] != key[i] and text[j] in bcs.keys(): 
  30. j += bcs[text[j]] 
  31. i = index 
  32. else: 
  33. j -= 1 
  34. i -= 1 
  35.  
  36. #---------------------- v2 ----------------------  
  37. def searchv2(text, key): 
  38. #removed string len functions from loop 
  39. len_text = len(text) 
  40. len_key = len(key) 
  41. i = len_key-1 
  42. index = len_key -1 
  43. j = i 
  44.  
  45. while True: 
  46. if i < 0: 
  47. return j + 1 
  48. elif j > len_text: 
  49. return "not found" 
  50. elif text[j] != key[i] and text[j] not in bcs.keys(): 
  51. j += len_key 
  52. i = index 
  53. elif text[j] != key[i] and text[j] in bcs.keys(): 
  54. j += bcs[text[j]] 
  55. i = index 
  56. else: 
  57. j -= 1 
  58. i -= 1  
  59.  
  60. #---------------------- v3 ---------------------- 
  61. def searchv3(text, key): 
  62. #from v2 plus modified 3rd if condition - breaking down the comparison for efficency, 
  63. #modified the while loop to include the first if condition (oppposite of it) 
  64. len_text = len(text) 
  65. len_key = len(key) 
  66. i = len_key-1 
  67. index = len_key -1 
  68. j = i 
  69.  
  70. while i >= 0 and j <= len_text: 
  71. if text[j] != key[i]: 
  72. if text[j] not in bcs.keys(): 
  73. j += len_key 
  74. i = index 
  75. else: 
  76. j += bcs[text[j]] 
  77. i = index 
  78. else: 
  79. j -= 1 
  80. i -= 1 
  81.  
  82. if j > len_text: 
  83. return "not found" 
  84. else: 
  85. return j + 1 
  86.  
  87.  
  88. key_list = ["POWER", "HOUSE", "COMP", "SCIENCE", "SHRIPHANI", "BRUAH", "A", "H"] 
  89.  
  90. text = "SHRIPHANI IS A COMPUTER SCIENCE POWERHOUSE" 
  91.  
  92. t1 = time.clock() 
  93. for key in key_list: 
  94. goodSuffixShift(key) 
  95. #print searchv1(text, key) 
  96. searchv1(text, key) 
  97. bcs = {} 
  98.  
  99. t2 = time.clock() 
  100. print 'v1 took %0.5f ms' % ((t2-t1)*1000.0) 
  101.  
  102. t1 = time.clock() 
  103. for key in key_list: 
  104. goodSuffixShift(key) 
  105. #print searchv2(text, key) 
  106. searchv2(text, key) 
  107. bcs = {} 
  108.  
  109. t2 = time.clock() 
  110. print 'v2 took %0.5f ms' % ((t2-t1)*1000.0) 
  111.  
  112. t1 = time.clock() 
  113. for key in key_list: 
  114. goodSuffixShift(key) 
  115. #print searchv3(text, key) 
  116. searchv3(text, key) 
  117. bcs = {} 
  118.  
  119. t2 = time.clock() 
  120. print 'v3 took %0.5f ms' % ((t2-t1)*1000.0) 

List of Keywords in Python

Remember that python is not a statically typed language, purely dynamic so look at the assignments to know what they are supposed to be.

t2 should be dealing with the time function.

def is a function declaration.

bcs is an array

key__list is a list

Everything else should be extremely easy to look at and interpret. While is a while loop, for is a for loop, ect…

As you can see, just from the base ones I told you the meaning of, it isn’t difficult to translate to C/C++, but no one is going to want to do the work for you for free.

Profile photo for Quora User

If you’re trying to take compiled machine code and turning it back to C, give up. It’s just not worth it.

There are no tools that do this well and even if you could build a tool, compiling code is a lossy process. It’s fundamentally impossible to recover the source code from machine language as a lot of information is discarded, such as functions and variable names as well as formatting.

Even if you had a tool that could convert machine language into compatible C code, it would be incredibly difficult to read and understand, and would take a ton of additional work to clean it up.

This is not a pr

If you’re trying to take compiled machine code and turning it back to C, give up. It’s just not worth it.

There are no tools that do this well and even if you could build a tool, compiling code is a lossy process. It’s fundamentally impossible to recover the source code from machine language as a lot of information is discarded, such as functions and variable names as well as formatting.

Even if you had a tool that could convert machine language into compatible C code, it would be incredibly difficult to read and understand, and would take a ton of additional work to clean it up.

This is not a project for someone to just take on individually for fun but could take months of work from a team of people to reverse-engineer machine code in a way that is actually human-readable.

A lot of stuff for the Arduino is open source, if you look into who developed the code you're trying to use, you probably could find the source code for it on their github or something. If the provider does not provide the source code, you could contact them and ask for it.

Otherwise, just don’t bother. It’s not worth it.

Profile photo for ImSyyd

It is possible to convert Java code to C code manually, but it is a time-consuming and error-prone process. There are also some tools that can assist with the conversion, such as "Java to C++" and "Java2C", but they may not produce reliable results and may require significant manual editing to correct errors.

Here are some general steps for manually converting Java code to C:

  • Replace all occurrences of "import" with "#include" to include the necessary C libraries.
  • Replace the Java "class" keyword with the C "struct" keyword, and replace all method declarations with function declarations.
  • Replace J

It is possible to convert Java code to C code manually, but it is a time-consuming and error-prone process. There are also some tools that can assist with the conversion, such as "Java to C++" and "Java2C", but they may not produce reliable results and may require significant manual editing to correct errors.

Here are some general steps for manually converting Java code to C:

  • Replace all occurrences of "import" with "#include" to include the necessary C libraries.
  • Replace the Java "class" keyword with the C "struct" keyword, and replace all method declarations with function declarations.
  • Replace Java data types with their equivalent C data types. For example, "int" in Java becomes "int" in C, "boolean" becomes "int", and "String" becomes "char*".
  • Replace Java operators with their equivalent C operators. For example, "&&" becomes "&&", "||" becomes "||", and "!" becomes "!".
  • Replace Java method calls with function calls.
  • Replace the Java "new" keyword with the appropriate C function calls to allocate memory for objects.
  • Replace Java exception handling with C error handling.

This is just a high-level overview of the process, and you will likely encounter many other issues and complications as you work through the conversion. It is generally recommended to rewrite the code in C rather than attempting to automatically convert it.

Profile photo for AlanM

Change the extension of the program file from .c to .cpp. The code will now compile with the C++ compiler. There will be probably a few things to fix, such as adding some casts to the code.

Profile photo for Himalay Goswami

Hello. So, you are a c++ programmer and want to convert it to an app. Now, it depends on platforms that you want to run your app on. You can easily build an executable for the machine you wrote your code on, or some similar configuration.

Now, you can run your code on android. For this, you will need a native development kit (NDK) which will be supported by Android Studio. You can download it from http://developer.android.com

iOS uses swift programming language, which is actually objective c (with modifications to suit the development environment). Now, you can convert your code to swift and get

Hello. So, you are a c++ programmer and want to convert it to an app. Now, it depends on platforms that you want to run your app on. You can easily build an executable for the machine you wrote your code on, or some similar configuration.

Now, you can run your code on android. For this, you will need a native development kit (NDK) which will be supported by Android Studio. You can download it from http://developer.android.com

iOS uses swift programming language, which is actually objective c (with modifications to suit the development environment). Now, you can convert your code to swift and get going.

However, c++ isn't used so broadly now a days. Languages like python and Go are taking over.

Profile photo for Kritomas

I don't think C++ has such functionality due to it being a compiled language, but you probably can write some kind of basic interpreter in C++ and run code through it. Basically, the same way Python solved it, which is written in C/C++

Profile photo for Thomas Schuetz

A2A. It depends to what degree… - Yes and No…

First of all - both languages are very different. So translation would not be an easy task, also when your C++ code would (for example) do something Python by design can’t (like executing Assembler), its pretty much over (except if you provide a library - written in C++, which then would provide Python with those abilities) - but then its getting really hacky…

Now, how could it be done:

When you are able to abstract all instructions - and provide an equivalent to any, you can basically translate it - even with a different syntax… - Programming languag

A2A. It depends to what degree… - Yes and No…

First of all - both languages are very different. So translation would not be an easy task, also when your C++ code would (for example) do something Python by design can’t (like executing Assembler), its pretty much over (except if you provide a library - written in C++, which then would provide Python with those abilities) - but then its getting really hacky…

Now, how could it be done:

When you are able to abstract all instructions - and provide an equivalent to any, you can basically translate it - even with a different syntax… - Programming languages always follow their Syntax, which makes translation possible (without the use of AI).

Now this might become a rather long example, but just to demonstrate you, how difficult it would be, even with a rather easy snippet of code - i’ll mostly be using Java throughout that demo:

Original C++ snippet:

  1. #include <iostream> 
  2. int n = 3; 
  3. if (n > 0) { 
  4. std::cout << "n is positive" << "\n"; 
  5. } 
  6. std::cout << "Bye World!" << "\n"; 

Now, first you’d want to split this into logic entities. We have 3 Entities - 1 Assignment, 1 If-clause and 1 function-call.

To split this, you’d probably use a RegularExpression as those are incredibly mighty when it comes to such use-cases - but that would really blow up this demo now, because you’d also have to differentiate between blocks that need or do not need curly braces… but lets assume, you have split that sourcecode into the following Strings:

  1. String[] entities = { 
  2. "#include <iostream>", 
  3. "int number = 3;", 
  4. "if (number > 0) { std::cout << "n is positive" << "\n"; }", 
  5. "std::cout << "goodbye cruel world." << "\n";" } 

Lets ignore the #include direction for now (I’ll come back to that later…)

Lets make an abstract class:

  1. public abstract class Entity { 
  2. public String toPython(); 
  3. public String toCpp(); 
  4. } 

Next, since “int number = 3;” is an Assignment, lets create a class AssignmentEntitty:

  1. public class AssignmentEntity extends Entity { 
  2. String targetType; 
  3. String traget; 
  4. String source; 
  5.  
  6. public String toPython() { 
  7. return target + " = " + source; 
  8. } 
  9.  
  10. public String toCpp() { 
  11. return targetType + " " + target + " = " + source + ";"; 
  12. } 
  13. } 

You’ll notice that i skipped the Constructor - to save a few lines…

For that If Clause - you’d also want to extend from Entity like so:

  1. public class IfEntity extends Entity { 
  2. ConditionEntity condition; 
  3. ArrayList<Entity> onTrue; 
  4. ArrayList<Entity> onFalse; 
  5.  
  6. public String toPython() { 
  7. return "if " + condition.toPython() + ":\n\t" + onTrue.toString();"; 
  8. } 
  9.  
  10. public String toCpp() { 
  11. return "if (" + condition.toCpp() + ") {" + onTrue.toCpp() + "}"; 
  12. } 
  13. } 

This code will not work - i’ve taken a few shortcuts to make it easier for the reader. You cant run “toPython()” on an ArrayList like that of course - you’d have to make another Entity and so on and so on - also that ConditionEntity does not exist yet - and maybe is not even necessary…

To create all those entities, you now parse that first Array and create those entities in the order they appear. - If you do everything right, you will end up with working Python-Code, when you call your top most toPython()… but - this is pure overkill!

About the “#include” directive, well - to make things even more complicated, you’d have to also add to every of your entities, if they require special includes, and keep track of those aswell…

I do not think that there will ever be a program to really translate C++ to Python, but… for sure this would be a great practice…

Back in 2002, i once had to write software that would translate bytecode coming from an MQL2-Compiler back to MQL. And that above approach was, what i used. It worked fine, but it was a hell of a work…

I hope this was not too boring, and could at least point you in a direction - as well as maybe help others with a similar Problem. Anyways - this answer is by no means in any way complete… - i just hope it helps…

About · Careers · Privacy · Terms · Contact · Languages · Your Ad Choices · Press ·
© Quora, Inc. 2025