c - 为什么我不能使用 gcc 生成 "Hello World"可执行文件?

标签 c gcc compilation terminal osx-yosemite

我正在尝试使用 GCC(基于 clang 和独立 GCC-4.9.2)编译我的第一个“Hello World”应用程序,但没有成功:

操作系统版本是 OS X Yosemite 10.10.2。

我正在使用以下代码 (main.c):

#include <stdlib.h>
#include <stdio.h>

int main (){
    printf("Hello World!");
    getchar();
    return 0;
}

然后我在终端中使用命令(XCode 附带的 clang)编译它:

gcc -o hello -c main.c

因此,在运行已编译的 hello 文件时出现以下错误:

MBP-Andrii:cTest andrii$ gcc -o hello -c main.c
MBP-Andrii:cTest andrii$ hello
-bash: /Users/andrii/avrTest/cTest/hello: Permission denied

如果我将 hello 文件的权限更改为 777 并再次出现新错误:

MBP-Andrii:cTest andrii$ chmod 777 hello
MBP-Andrii:cTest andrii$ hello
Killed: 9
MBP-Andrii:cTest andrii$

同样的事情发生在独立的 GCC-4.9.2 上。

我猜这可能与输出二进制格式或编译器缺少一些标志有关。

最佳答案

从您用于编译应用程序的命令中删除 -c

-c 告诉编译器只编译和汇编但不链接。使用 -c 时,您实际上并不是在创建应用程序。

参见 GCC Manual :

-c

Compile or assemble the source files, but do not link. The linking stage simply is not done. The ultimate output is in the form of an object file for each source file.

By default, the object file name for a source file is made by replacing the suffix ‘.c’, ‘.i’, ‘.s’, etc., with ‘.o’.

Unrecognized input files, not requiring compilation or assembly, are ignored.

关于c - 为什么我不能使用 gcc 生成 "Hello World"可执行文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29183017/

相关文章:

c++ - 在循环中声明变量是否有效?

c++ - 是否有 gcc 标志允许在 C++ 中进行 C 风格的隐式指针转换?

qt - 如何在 Ubuntu 上使用 QT 库

c++ - QT 版本、套件和编译器

c - 关于二进制 "bit position"命名法

c - 堆栈变量损坏? C

c - 添加 IBO 时基本的 opengl 黑屏

c++ - 运算符重载代码编译错误,模板参数推导/替换失败

java - 为什么参数化构造函数会出现此错误?

linux - 基于 ARM 的处理器上的编译器标志