在Mac上编译C ++代码

时间:2011-04-07 13:42:54

标签: c++ gcc namespaces std

我想在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

到目前为止回答答案(非常感谢),我把(!)命名空间声明放回去了,但这并没有带来成功,但是:

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

3 个答案:

答案 0 :(得分:6)

您需要添加

using namespace std;

或限定您使用该命名空间中的符号,如

std::cout << "Hello, world!";

所以让符号可见(你也想添加换行符....)。

答案 1 :(得分:0)

#include <iostream>

using namespace std; // <<< you forgot this !

int main ()
{
  cout<<"Hello World!";
  return 0;
}

答案 2 :(得分:0)

您必须使用namespace std;

添加
#include <iostream>

using namespace std;

int main ()
{
  cout<<"Hello World!";
  return 0;
}