Sublime Forum

C Build System

#1

Dear Experts, I have a query. I want to compile C files using Sublime Text.
Well I got a solution. Made a “New Build System” . Pasted this code :


{
“shell_cmd” : “gcc $file_name -o ${file_base_name}”,
“working_dir” : “$file_path”,

“variants”:
[
{
“name”: “Run”,
“shell_cmd”: “gcc $file_name -o ${file_base_name} && ${file_path}/${file_base_name}”
}
]
}


But there is a problem.
If my C file name have spaces then it shows errors. If there is no spaces in the C file name, it compiles well.

I know the problem is of GCC Command.

But I want to ask that, if there is any way to modify the above “Build System” code , so that it can compile C file names which have spaces in them?

0 Likes

#2

When the shell on your operating system parses commands, it uses spaces to know where arguments begin and end. So if you have a filename with spaces, the shell thinks that only the first part of the filename is the file and the rest is arguments, and things go poorly.

In order to get around that you need to add double quotes around any arguments that might inherently contain spaces; the double quotes tell the shell that you meant to use a single argument there.

For example, in a terminal, you would do something like:

gcc "my file name with spaces.c" -o "my file name with spaces"

Since the sublime-build is a JSON file and double quote characters are special in JSON, you need to quote the double quote characters.

For your shell_cmd, that would look like:

"shell_cmd" : "gcc \"$file_name\" -o \"${file_base_name}\"",

Something to note is that the location the file is stored in can also contain spaces, so you need to do the same thing with $file_path as well, for examle.

WIth all that said, the C++ Single File.sublime-build that ships with Sublime already does what you’re trying to do in your custom build, including making sure that it only applies to C/C++ and being able to detect error messages for you so that you can navigate between them, so you may want to just use that build instead of making your own.

1 Like