簡體   English   中英

C ++:在mac osx上使用帶有gcc的std :: cout

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

我是C ++編程的新手,我嘗試在終端上使用gcc在mac上進行我的第一次練習。

不幸的是,由於與iostream相關的問題,我無法編譯。 使用簡單的程序:

#include <iostream>

int main()
{

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

它給了我錯誤:

error: ‘endl’ was not declared in this scope

刪除cout << endl; line給了我這些錯誤:

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

很明顯,iostream標頭沒有正確鏈接。 我試過“<”iostream.h“>”和“iostream.h”沒有成功。

有人有任何可以幫助我的提示嗎? 謝謝!

你需要使用std::endl; - 整個標准庫位於std命名空間中。 它看起來像你在命令行上使用gcc而不是g++ 后者自動執行正確鏈接C ++所需的步驟。

endl; 屬於std命名空間

您的2個選項如下:

1)聲明你的命名空間,例如

#include <iostream>
using namespace std;

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

或者使用std::endl; 例如

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

看看哪一個適合你。 我建議1)(檢查我沒有做std::cout因為我已經聲明了我的命名空間)因為它有助於減少輸入std:: everytime。

你只需要使用std::endl; 或者,更好的是,使用方便的using指令:

#include <iostream>

using namespace std;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM