Compiling a Matlab C code with GCC/G++

In this post, I am sharing how to compile a C code generated by Matlab C coder with GCC compiler. Let me explain with an example.

1. Generating a C code with Matlab C coder.

I will use a very simple Matlab code, and the below is the code

function y = add_coder(a,b)
y=a+b

With the Matlab C coder, let’s auto-generate the C code. You have to specify the types of variables and some other options. If you just read the dialog box, it might not be difficult.

As a result, you can see this kind of result. If your Matlab version is not 2015, it might be little different, but its big flow is almost same.

directory_matlab_coder

 

2. Let’s compile the code generated by Matlab C coder

This is my main.cpp file that is modified from the auto-generated main.cpp by Matlab C coder

#include "rt_nonfinite.h"
#include "add_coder.h"
#include "add_coder_terminate.h"
#include "add_coder_initialize.h"
#include "stdio.h"

int main()
{
  /* Initialize the application.
     You do not need to do this more than one time. */
  add_coder_initialize();

  /* Invoke the entry-point functions.
     You can call entry-point functions multiple times. */
  double a=10;
  double b=20.0;
  double y;
  y = add_coder(a, b);
  printf("y: %lf\n",y);

  /* Terminate the application.
     You do not need to do this more than one time. */
  add_coder_terminate();
  return 0;
}

I located this main.cpp file with other all codes.

Now let’s compile all codes. Just compile main.cpp with all other cpp files. like this.

compilation_example

 

I am attaching all related files as a zip file. <Download>

 

Isn’t it easy??!!!

Have a good day~~!

6 thoughts on “Compiling a Matlab C code with GCC/G++

  1. Harbinger

    Thank you,i was just being an idiot and trying to compile just my main source file instead of all the ones with extension .c/.cpp,until i found this article…just a correction though,main’s arguments at line 7 need to have names,otherwise you get the error “parameter name omitted”

    Reply
    1. admin Post author

      The error occurs depending on the type of compiler. Some compilers do not care for the names of input parameters, and some compilers care about it. But it is a good practice to use a name for the input parameters. Thanks for letting me know this one. And I am happy to hear that you get some helps from my blog.

      Reply
  2. Xuezhou Zhang

    Are you able to run add_coder as a real function that takes two input and print an output? The way the main file is right now makes add_coder no longer a function. Can you do a demo on that? I’ve been puzzled for a while.

    Reply

Leave a Reply