C programming with Sublime Text

C is one of my favourite programming languages and Sublime Text one of my favourite text editors. However, I didn't use to code in C with Sublime, don't ask me why. When I decided to combine them the first issue I faced was how to integrate makefiles to Sublime.

As I like to trust on my own building enviroment I will write a custom build system. If we go to Tools->Build System->New Build System..., we can create a new build configuration. Configuration is made by means of a JSON file. Following the one we need to use a makefile to compile our code.

 1 {
 2  "cmd": ["make"],
 3  "selector": "source.makefile",
 4  "variants":
 5  [
 6      {
 7          "name": "Clean",
 8          "cmd": ["make", "clean"]
 9      },
10      {
11          "name": "All",
12          "cmd": ["make", "all"]
13      }
14  ]
15 }

Variants will be used to call make clean and make all using a Sublime custom shortcut. So... how do we create the shortcut? Easy. Another JSON file.

If we go to Preferences->Key Bindings-User we can add the shortcuts we want to the existing JSON file.

1 [
2 
3     { "keys": ["ctrl+shift+a"], "command": "build", "args": {"variant": "All"} },
4 
5     { "keys": ["ctrl+shift+c"], "command": "build", "args": {"variant": "Clean"} },
6 
7 ]

And that's it. To sum up a simple example of how we can use this configuration. We create a simple C program.

1 /*File: hello.c*/
2 #include <stdio.h>
3 int main(void)
4 {
5   printf("Hello Sublime!\n");
6   return 0; 
7 }

And now, our makefile.

 1 CFLAGS = -ansi -pedantic -Wall -O3
 2 CC = gcc
 3 all: hello.c
 4 hello: hello.o
 5  $(CC) hello.o -o hello
 6 hello.o: hello.c
 7  $(CC) $(CFLAGS) -c -o hello.o hello.c 
 8 
 9 .PHONY: clean
10 clean:
11  rm -f *.0 *~

Ready. If we put this files under the same folder, and we press Ctrl+Shift+A with the scope in our makefile, sublime will call make all and we will have our little program compiled. Sublime will show us the output of the compilation process and we will know if everything went well.

We can also run the program with a shortcut from Sublime. However, I prefer to run the code directly from a terminal as we can take advantage of the full functionality of the terminal.

For a snippet of code like this, we can use a simpler compilation script, or maybe use Sublime default compilation system. Let's see how to do that.

Compiling a single file

In this case we have to create a custom compiling script as follows.

1 {
2   "cmd" : ["gcc $file_name -o $file_base_name -ansi -pedantic -Wall -lm"],
3   "selector" : "source.c",
4   "working_dir" : "$file_path",
5   "shell" : "true"
6 }

For the record, this article was written using Sublime Text 3

Written on March 27, 2015