简体   繁体   English

如何在Mac OS X上编译运行C程序

[英]How to compile and run C program on Mac OS X

I am learning C and wish to write the program using a text editor on my Mac (running OS X v10.7 (Lion)).我正在学习 C 并希望在我的 Mac(运行OS X v10.7 (Lion))上使用文本编辑器编写程序。

I write the .c file, and compile it using gcc filename.c - which creates executable file called a.out .我编写了.c文件,并使用gcc filename.c对其进行编译 - 这会创建名为a.out的可执行文件。 However, when I type a.out or /a.out , I get the following messages:但是,当我键入a.out/a.out时,我收到以下消息:

-bash: a.out: command not found or -bash: /a.out: -bash: a.out: command not found or -bash: /a.out:
No such file or directory无此文件或目录

I have successfully compiled and ran C programs on Linux systems before using this same method.在使用相同的方法之前,我已经在 Linux 系统上成功编译并运行了 C 程序。 What am I doing wrong on my Mac?我在 Mac 上做错了什么?

您需要添加一个点来指示可执行文件位于当前目录中,因为当前目录不在路径中:

./a.out

You're just missing one thing! 你只是缺少一件事! Instead of "/a.out" it should be "./a.out". 而不是“/a.out”它应该是“./a.out”。 Another useful thing is changing the output so that you can have multiple compiled programs. 另一个有用的东西是更改输出,以便您可以拥有多个已编译的程序。 Simply, the only thing you need to put in the terminal is the following (fill in the blanks with what you would like) 简单地说,您需要在终端中放置的唯一内容如下(用你想要的东西填空)

gcc nameofprogramyouwrote.c -o whatyouwanttheprogramtobenamed

good luck! 祝好运!

You have to add a dot in front of the slash: 你必须在斜线前添加一个点:

./a.out

/a.out would try to execute a program in the root folder ( / ). /a.out将尝试在根文件夹( / )中执行程序。
a.out will look for your program in all the folders defined in the PATH environment variable. a.out将在PATH环境变量中定义的所有文件夹中查找您的程序。

I have successfully compiled and ran C programs on Linux systems before using this same method. 在使用相同的方法之前,我已经在Linux系统上成功编译并运行了C程序。 What am I doing wrong on my Mac? 我在Mac上做错了什么?

You have to do the same on Linux. 你必须在Linux上做同样的事情。

确保使用chmod + x a.out设置可执行文件的权限

To build: 建立:

    gcc -Wall -o yourFile yourFile.c

Then to execute: 然后执行:

    ./yourFile

But you forgot the dot,但是你忘记了那个点,

./a.out

also you can just use cmake to compile your C program into binary if ./a.out doesn't work!如果./a.out不起作用,你也可以只使用 cmake 将你的 C 程序编译成二进制文件!

You'll need a compiler. 你需要一个编译器。 The easiest way however is to install XCode. 然而,最简单的方法是安装XCode。 This way you'll get access to "gcc", Thus, 通过这种方式,您可以访问“gcc”,因此,

gcc -o mybinaryfile mysourcefile.c

Then run it like this. 然后像这样运行它。

./mybinaryfile

Hope this helps!. 希望这可以帮助!。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM