如何在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

 

转载于:https://www.cnblogs.com/fatoland/p/9858019.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值