Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Using std::cout with gcc on a mac osx

Tags:

c++

macos

I'm new to C++ programming and I try to make my first exercise on a mac using gcc in the terminal.

Unfortunately, I can't compile because of issues related to iostream. With a simple program as:

#include <iostream>

int main()
{

 std::cout << "hello world";
 std::cout << endl;
 return 0;
}

it gives me the error:

error: ‘endl’ was not declared in this scope

removing the cout << endl; line gives me these errors:

Undefined symbols:
  "___gxx_personality_v0", referenced from:
      ___gxx_personality_v0$non_lazy_ptr in cceBlyS2.o
  "std::ios_base::Init::~Init()", referenced from:
      ___tcf_0 in cceBlyS2.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 cceBlyS2.o
  "std::ios_base::Init::Init()", referenced from:
      __static_initialization_and_destruction_0(int, int)in cceBlyS2.o
  "std::cout", referenced from:
      __ZSt4cout$non_lazy_ptr in cceBlyS2.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

It's evident that the iostream header is not properly linked. I tried "<"iostream.h">" and "iostream.h" with no success.

Does anybody has any hint that could help me? Thanks!

like image 658
Patof Avatar asked Feb 12 '10 06:02

Patof


2 Answers

You need to use std::endl; -- the entire standard library is in the std namespace. It also looks like you used gcc instead of g++ on the command line. The latter automatically does the steps necessary to link C++ correctly.

like image 92
Jerry Coffin Avatar answered Oct 05 '22 21:10

Jerry Coffin


endl; falls under the std namespace

your 2 options are as follows:

1) declaring your namespace, e.g.

#include <iostream>
using namespace std;

int main() {
 cout << "hello world";
 cout << endl;
 return 0;
}

or using std::endl; e.g.

 std::cout << "hello world";
 std::cout << std::endl;
 return 0;

See which one suits you. I recommend 1) (Check that I didn't do std::cout because I've declared my namespace already) as it helps to reduce typing std:: everytime.

like image 34
Buhake Sindi Avatar answered Oct 05 '22 21:10

Buhake Sindi