我想在Mac上编写非常简单的C++程序,但出现错误。我没有使用C++(和gcc)的丰富经验,网络上的简单指南也没有讨论此主题。

请看一下我简单的hello world程序:

erik2:~[03:38 pm]$ cat hw.cpp
#include <iostream>

int main ()
{
  cout<<"Hello World!";
  return 0;
}
erik2:~[03:38 pm]$ gcc hw.cpp
hw.cpp: In function ‘int main()’:
hw.cpp:5: error: ‘cout’ was not declared in this scope

到现在为止(非常感谢)响应答案,我放回了(!) namespace 声明,但这并不会成功:
erik2:~[03:51 pm]$ cat hw.cpp
using namespace std;
#include <iostream>

int main ()
{
  cout<<"Hello World!";
  return 0;
}
erik2:~[03:51 pm]$ gcc hw.cpp
Undefined symbols:
  "___gxx_personality_v0", referenced from:
      ___gxx_personality_v0$non_lazy_ptr in ccphDFtO.o
  "std::ios_base::Init::~Init()", referenced from:
      ___tcf_0 in ccphDFtO.o
  "std::basic_ostream<char, std::char_traits<char> >& std::operator<<     <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)",     referenced from:
      _main in ccphDFtO.o
  "std::ios_base::Init::Init()", referenced from:
      __static_initialization_and_destruction_0(int, int)in ccphDFtO.o
  "std::cout", referenced from:
      __ZSt4cout$non_lazy_ptr in ccphDFtO.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

最佳答案

您需要添加

using namespace std;

或限定您使用该 namespace 中的符号
std::cout << "Hello, world!";

因此,使符号可见(并且您还想添加换行符...。)。

关于c++ - 在Mac上编译C++代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5582154/

10-13 08:25