如何在macOS的Terminal上运行C程序

 

源代码编辑器程序员


为了简化编写代码的流程,每一位程序员都须要选择一款适合本身的源代码编辑器,笔者目前使用的编辑器为Visual Studio Codexcode

 

源代码编辑器


源代码编辑器安装完成后,开始编写一段简单的C代码。工具

 1 #include <stdio.h>
 2 
 3 int main(void)  4 {  5   int num;  6   num = 1;  7 
 8   printf("I am a simple ");  9   printf("computer. \n"); 10   printf("My favorite number is %d because it is first.\n", num); 11 
12   return 0; 13 }

接着将源代码保存为符合系统要求的文件:first.c。开发工具

 

编译器spa


要在Terminal上运行C程序,必须先使用编译器将源代码文件编译为可执行文件,Apple提供的开发工具Xcode中就包含了可用的编译器:Clang。code

依次点击 Finder > Applications > App Store ,在Search栏内输入Xcode,而后在搜索结果中找到Xcode,点击“GET”便可安装该程序。blog

接下来须要在Terminal终端界面中安装command line developer tools,依次点击 Finder > Applications > Utilities > Terminal ,将弹出以下界面。开发

输入如下命令:terminal

xcode-select --install

将会弹出安装提示:

点击Install,并在接下来弹出的许可协议界面中点击“Agree”,以后等待安装完成便可。

 

编译


安装完编译所需的工具后,在Terminal界面中输入命令,将当前目录切换到源代码文件所在的目录。

cd /Users/falcon424/development/c-demo

接着对源代码文件执行编译操做(指令中的 -o 意为将目标文件编译为指定文件名的可执行程序)。

clang first.c -o first

 

运行


编译成功后,在Terminal界面中运行刚建立的可执行程序。

./first

输出结果以下:

I am a simple computer. 
My favorite number is 1 because it is first.

 

参考


https://stackoverflow.com/questions/32337643/how-to-run-c-program-on-mac-os-x-using-terminal#
《C Primer Plus (第6版)中文版》,Stephen Prata

相关文章
相关标签/搜索