How to Run and Compile .c on Sublime Text 2 [MAC O

2019-02-10 00:04发布

问题:

I am learning C at college now, and teachers told me to use codeblocks as an IDE, but in my opinion codeblocks is a bit ugly and that's why I've chosen Sublime Text 2, the BEST IDE/Text Editor out there.

At the moment I write my code via sublime, save it and then compile it via mac os terminal (gcc) and than run it on the terminal as well...

What I want to know, if it is even possible, is how to do it right from sublime, using its console or a plugin (or something), in other words I want to know if it is possible to compile my .c and run it with only e few clicks right on sublime... (for now I am just building console applications)

I've read some posts here about this topic but none of those helped me to solve this.

回答1:

A basic C build file could look like this:

{   
"cmd" : ["/path/to/gcc", "$file_name", "-o", "${file_base_name}", "-lgsl", "-lgslcblas", "-lm" , "-Wall"],
"selector" : "source.c",
"shell":false,
"working_dir" : "$file_path",

"variants":
    [
        {
            "name": "Run",
            "cmd": ["bash", "-c", "/path/to/gcc '${file}' -Wall -o '${file_path}/${file_base_name}' && '${file_path}/${file_base_name}'"]
        }
    ]
}

To just compile you press command + b.

To compile then run you would press command + shift +b

The only thing you need to do is put the path to your gcc and inlcude the libraries you use (I left some GSL stuff for this example). The $_variables are sublime build system variables and should not be changed. For more info on those variables, look here.

You can put the actual build system file here:

~/Library/Application Support/Sublime Text 2/Packages/User/C.sublime-build


回答2:

I used the following as a .sublime-build to compile and run C. Basically an edit of the code used for C++. Worked for me.

{
"cmd": ["gcc", "${file}", "-o", "${file_path}/${file_base_name}"],
"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
"working_dir": "${file_path}",
"selector": "source.c",

"variants":
[
    {
        "name": "Run",
        "cmd": ["bash", "-c", "gcc '${file}' -o '${file_path}/${file_base_name}' && '${file_path}/${file_base_name}'"]
    }
]
}


回答3:

If you are using a makefile you could use something like this:

{   
"cmd" : ["/usr/bin/make"],
"selector" : "source.c",
"shell":false,
"working_dir" : "$file_path",

"variants":
    [
        {
            "name": "Run",
            "cmd": ["bash", "-c", "/usr/bin/make && '${file_path}/${file_base_name}'"]
        }
    ]
}