This is an old revision of the document!


Very brief guide to working with C

The following section has been tested on: macOS High Sierra (10.13.6), Matlab 2014b, XCode 10.1

One might have to work with C to meddle with low-level codes for softwares, or for developing new programs. There are different kinds of files for C:

  1. source files (.c): The main code goes here. References some headers and object files. The source file is compiled to give us our program.
  2. header files (.h): Function declarations, preprocessor statements.
  3. object files (.o): Output of the compiler, but not executable by themselves, but its functions can be called by other programs without having to recompile the functions.
  4. binary executable (.exe, .mex, etc..): executable output program. Mex (matlab executable) format is used by c source codes compiled for use by Matlab functions.

Refs: http://courses.cms.caltech.edu/cs11/material/c/mike/misc/compiling_c.html

Compiling in C

To compile a source code into object or executive files, one uses a compiler (for instance, gcc or clang). Flags:

  • [-c foo.c] : compiles the foo.c source file
  • [-o foo.o] : specifies the output of the compilation
  • [-g] : allows debuggers to be run on the output files
  • [-frameworks framework] : adds the framework libraries to be compiled with the source code.

Debugging in C (lldb or gdb)

In order to debug files in C on MacOS use lldb. On other systems, you can use gdb (gdb deosn't work as well on macOS).

Basic commands:

  • To import frameworks into the debugger (for instance, CoreGraphics for CG functions):
     expr -l objective-c -- @import CoreGraphics 
  • step
  • p : evaluates an expression (same as expr)
  • parray : prints c arrays in a readable format

Debugging in C (Matlab mex files)

You can debug mex files that are called by matlab functions. The steps are outlined here but I outline them here again. The debugging process works through XCode debugger, which can be programmed to be triggered by Matlab Executable.

  1. We want to debug a function whos source code is, for instance, yprime.c
  2. Recompile source mex file with debugging symbols
     mex -g yprime.c 
  3. Create a new XCode workspace, and configure it to use for debugging
    1. Add the file(s) to be debugged into the XCode workspace
    2. Create a scheme
    3. Set a symbolic breakpoint (this allows the debugger not to stop on communication signals between the apps)
    4. Set breakpoints in the mex file
  4. Start the Xcode debugger
  5. Launch a new instance of matlab from terminal
  6. Run the mex file