简体   繁体   English

通过命令行在OS X上编译简单的Hello World程序

[英]Compiling simple Hello World program on OS X via command line

I've got a simple hello world example that I'm trying to compile on OS X, named hw.cpp : 我有一个简单的hello world示例,我正在尝试在OS X上编译,名为hw.cpp

#include <iostream>
#include <string>
using namespace std;
int main() {
  cout << "Hello world!" << endl;
  return 0;
}

I'd like to compile it using gcc , but I've had no success. 我想用gcc编译它,但我没有成功。 I'd also like to hear the other options, like using Xcode ? 我还想听听其他选项,比如使用Xcode?

Try 尝试

g++ hw.cpp
./a.out

g++ is the C++ compiler frontend to GCC. g++是GCC的C ++编译器前端。
gcc is the C compiler frontend to GCC. gcc是GCC的C编译器前端。

Yes, Xcode is definitely an option. 是的,Xcode绝对是一个选择。 It is a GUI IDE that is built on-top of GCC. 它是一个构建在GCC之上的GUI IDE。

Though I prefer a slightly more verbose approach: 虽然我更喜欢稍微冗长的方法:

#include <iostream>

int main()
{
    std::cout << "Hello world!" << std::endl;
}
g++ hw.cpp -o hw
./hw
user@host> g++ hw.cpp
user@host> ./a.out

Compiling it with gcc requires you to pass a number of command line options. 使用gcc编译它需要您传递许多命令行选项。 Compile it with g++ instead. g++编译它。

The new version of this should read like so: 这个的新版本应如下所示:

xcrun g++ hw.cpp
./a.out

You didn't specify what the error you're seeing is. 您没有指定您所看到的错误。

Is the problem that gcc is giving you an error, or that you can't run gcc at all? 问题是gcc给你一个错误,或者你根本不能运行gcc

If it's the latter, the most likely explanation is that you didn't check "UNIX Development Support" when you installed the development tools, so the command-line executables aren't installed in your path. 如果是后者,最可能的解释是您在安装开发工具时未检查“UNIX开发支持”,因此命令行可执行文件未安装在您的路径中。 Re-install the development tools, and make sure to click "customize" and check that box. 重新安装开发工具,并确保单击“自定义”并选中该框。

Use the following for multiple .cpp files 将以下内容用于多个.cpp文件

g++ *.cpp
./a.out

此外,您可以使用像CLion(JetBrains)这样的IDE或像Atom这样的文本编辑器,使用gpp-compiler插件,就像一个魅力(F5编译和执行)。

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

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