Is there a way to turn off code for compilation with coder?

6 views (last 30 days)
I have a function that I want to encode in C++ with Matlab Coder. The function I want to encode incorporates elements that the Coder cannot convert to C++. If I were programming in C/C++, I could use preprocessing directives to avoid most of the places in my code that cause the problems, such as try/catch blocks. Is there a way to do this in Coder? For example consider the code below:
function u=foo(a)
try
if a==5
throw(MException('foo:BadInput','Input cannot be 5.');
end
u=a+2;
catch mxc_Error
% Handle errors here
end
In a language like C/C++, I could put something like #ifdef statements around the try and catch statements to disable them when the code is compiled under certain conditions. Is there a way to do something in Matlab Coder where certain statements are ignored by Matlab but used by the Coder?
Keep in mind that the reason I ask is because I want to write code that I can use in both Matlab and C++. If I just wanted my code in C++, I would not have a problem because I could use Coder directives (or better still, just write my code in C++ to begin with). However, Coder directives cause Matlab to fail on machines that do not have the Coder, which is not the behavior I am looking for, since I need to share my m-files.

Answers (1)

Ryan Livingston
Ryan Livingston on 16 Oct 2012
Hi Alan,
The function coder.target() can be used to eliminate code from generation:
if isempty(coder.target())
% code which should only run in MATLAB
end
This can also allow you to fine-tune your code depending upon the target for which you are generating code.
It should not require a MATLAB Coder license and comes with base MATLAB. Is this not the behavior which you see?
  1 Comment
Alan Ford
Alan Ford on 17 Oct 2012
Yes, I can use coder.target() for some things, such as avoiding throw statements, which the coder does not support. However, I would really like to do something like the following:
if isempty(coder.target())
try
end
% Various matlab statements here
if isempty(coder.target())
catch ml_exception
% Do something here
end
end
This is more like what preprocessing directives do for you in C/C++, which would be really handy, given that you could use try and catch while developing code in Matlab for testing, and then turn off those features when you convert the code to C/C++. Unfortunately, the syntax of Matlab prevents the code above from running, at least on my machine.

Sign in to comment.

Categories

Find more on MATLAB Coder in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!