【问题标题】:extreme newbie - hello world error极端新手 - 你好世界错误
【发布时间】:2011-12-11 19:25:46
【问题描述】:

使用 B. Stroustrup 的 Programming text 和关于 pg 50 的“hello world”程序会出错。我对“std_lib_facilities.h”包含文件有疑问。

运行(以 root 身份)“gcc hworld1.cpp”后,输出为 -

In file included from /usr/include/c++/4.4/ext/hash_map:60,
             from std_lib_facilities.h:34,
             from hworld1.cpp:1:
/usr/include/c++/4.4/backward/backward_warning.h:28: warning: #warning This file     includes at least one deprecated or antiquated header which may be removed without further notice at a future date. Please use a non-deprecated interface with equivalent functionality instead. For a listing of replacement headers and interfaces, consult the file backward_warning.h. To disable this warning use -Wno-deprecated.
/tmp/ccpwXUYx.o: In function `main':
hworld1.cpp:(.text+0x14): undefined reference to `std::cout'
hworld1.cpp:(.text+0x19): undefined reference to `std::basic_ostream<char,     std::char_traits<char> >& std::operator<< <std::char_traits<char>  >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
/tmp/ccpwXUYx.o: In function `__static_initialization_and_destruction_0(int, int)':
hworld1.cpp:(.text+0x41): undefined reference to `std::ios_base::Init::Init()'
hworld1.cpp:(.text+0x46): undefined reference to `std::ios_base::Init::~Init()'
/tmp/ccpwXUYx.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status

对如何修复文件有任何建议,也许注释掉哈希部分?

很高兴终于有时间开始,但这似乎比第一次故障排除任务要大一些。我试过只使用 iostream 作为包含。我在 Ubuntu 11.04 上运行它。也许我需要更新 gcc 或使用 g++。不知道什么可以让我通过这个。我尝试了一些使用 'using ... std' 和 ... 作为我不记得的适当名称的东西(哎呀)。任何人都知道正确的包括。

这里是代码 -

#include "std_lib_facilities.h"

int main()
{
    cout<<"hiya people\n";
    return 0;
}

【问题讨论】:

  • 使用g++编译和链接C++。
  • @Mark: Stroustrup 有more than one book
  • 请不要以 root 身份进行操作。

标签: c++


【解决方案1】:

你应该使用 g++,因为 gcc 是 C 编译器(不是 C++)。

【讨论】:

  • 这是真的。虽然 gcc 是一个 C++ 编译器,但它不会自动与 stdlib 链接。
【解决方案2】:

这应该可以解决它。

#include <iostream>

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

话虽如此,但本书可能出于某种原因希望您以某种方式做到这一点。这些错误是链接时错误,在代码被编译后,它需要与其他经过编译的代码以及头文件一起链接,应该有一个 lib 文件。您需要将其添加为编译器参数。

编辑:经过进一步检查,似乎缺少的“链接”是标准库,这并不奇怪,因为您使用的是 gcc 而不是 g++,它会自动与标准库链接。

【讨论】:

  • @Mat:是的,我就是这样做的。我只是在我的答案中猛拉并粘贴。
  • endl\n 不同,除非您真的想刷新缓冲区,否则不应使用它。在出口附近冲水是多余的。
  • 我知道这一点,尽管我认为在 hello world 的情况下你会想要刷新缓冲区。 (虽然我认为缓冲区在流析构函数中刷新)
  • Bjarne 创建特殊头文件的要点之一是包含大量的包含和其他与本书一起使用的功能。在某些时候,我添加的 iostream 是不够的,所以如果有更多的烫发。解决方法很棒。现在我可以继续...
【解决方案3】:

使用头文件 iostream 而不是你正在使用的那个。

还要确保您使用的是 g++ 而不是 gcc。由于 gcc 是 C 的编译器,而 g++ 是 C++ 的编译器

【讨论】:

    猜你喜欢
    • 2014-10-24
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    相关资源
    最近更新 更多