开发者

Compiling C++ code on Mac

I want to write very simple C++ programs on my Mac but I get errors. I don't have a lot of experience with C++ (and gcc) and the simple guides on the web also don't discuss this topic.

Please have a look at my simple hello world program:

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

Responding to the answers until now (thanks a lot), I put back(!) the namespace declaratation, but that doesn't result in a success, though:

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


You need to either add

using namespace std;

or qualify your use of symbols from that namespace as in

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

so make the symbol visible (and you also want to add a newline....).


#include <iostream>

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

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


You must add using namespace std;

#include <iostream>

using namespace std;

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜