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

 

源代码编辑器


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

 

源代码


源代码编辑器安装完成后,开始编写一段简单的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。

 

编译器


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

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

接下来需要在Terminal终端界面中安装command line developer tools,依次点击 Finder > Applications > Utilities > 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

 

posted @ 2018-10-28 13:03  Falcon424  阅读(681)  评论(0编辑  收藏  举报