0

I am using Matlab coder to port code to C, e.g. for the next function:

function sum_out = my_sum( x )
sum_out = 0;
for i=1:size(x,1)
    sum_out = sum_out + x(i);
end
end 

The generated C code is:

double my_sum(const double x[10])
{
  double sum_out;
  int i;
  sum_out = 0.0;
  for (i = 0; i < 10; i++) {
    sum_out += x[i];
  }
  return sum_out;
}

Is there a way to make the indentation 4 spaces?

Also, I would like to have the curly brackets in a separate line.

1 Answer 1

1

If you have Embedded Coder, the configuration settings IndentSize and IndentStyle allow you to tweak the behavior you've requested:

https://www.mathworks.com/help/coder/ref/coder.embeddedcodeconfig.html?s_tid=doc_ta

More generally, if you're looking for further customization of the generated code's formatting, you could consider running an external code formatting tool on it like clang-format.

The answer:

https://www.mathworks.com/matlabcentral/answers/391533-is-there-a-way-to-disable-line-wrapping-in-generated-c-code-from-matlab-coder

shows how you could automate that. I'll reproduce the steps here for completeness.

The Coder config setting PostCodeGenCommand allows you to run some MATLAB code after code generation finishes but before the C/C++ compiler runs. So you can use that to call clang-format.

  • Make the file doclangformat.m:

    function doclangformat(buildInfo)
    sourceFiles = join(buildInfo.getSourceFiles(true,true));
    sourceFiles = sourceFiles{1};
    cmd = ['clang-format -i -style=''{BasedOnStyle: LLVM, ColumnLimit: 20}'' ' sourceFiles]; 
    system(cmd);
    

    I've set ColumnLimit to 20 so the effect is obvious. The code will be drastically wrapped. You can view the other options in the clang-format documentation.

  • Set up the configuration object and call codegen:

    cfg = coder.config('lib');
    cfg.PostCodeGenCommand = 'doclangformat(buildInfo)';
    codegen foo -config cfg <other codegen args>
    

Now you should see that your code is wrapped to about 20 columns.

The main downside of this approach is that the other Coder style settings like IndentStyle, IndentSize, etc. will need to be specified in your clang-format specification.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.