c++ - GCC 4.4 fails to link valid C++11 code, when options are -std=C++0x -O0

标签 c++ linux c++11 g++

这是一个基于第一个答案的编辑问题。其他人向我指出,我认为无效的代码在 C++11 中完全没问题。然而,gcc 的行为因不相关的内容而异。


有一个文件,包含

std::string logFilePath;
/*...*/
std::ofstream logfile(logFilePath, std::ofstream::trunc);

此行在 windows (MSVC2010) 和 linux (G++4.4) 下编译和链接 -std=c++0x 设置。当我提供 -O0 选项时,链接中断并给出错误:

 undefined reference to `std::basic_ofstream<char, std::char_traits<char> >::basic_ofstream(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::_Ios_Openmode)'

问题是为什么会发生这种情况?这似乎是 gcc 中的错误,但任何进一步的信息都会很好。

有一个旧的thread关于同样的问题,这导致我 -Ox 成为罪魁祸首,但没有解释,只有解决方案提示。


这是一个最小的例子:

#include <string>
#include <fstream>
#include <iostream>

int main (int, char**)
{
    std::string name = "name";
    std::ofstream stream(name, std::ofstream::trunc);
    return 0;
}

然后:

$ /usr/bin/g++44 -std=c++0x main.cpp -Wall -O1
$ /usr/bin/g++44 -std=c++0x main.cpp -Wall -O0
    /tmp/ccBjIuWi.o: In function `main':
    main.cpp:(.text+0x80): undefined reference to `std::basic_ofstream<char, std::char_traits<char> >::basic_ofstream(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::_Ios_Openmode)'
    collect2: ld returned 1 exit status

第一行编译正常,并给出预期的行为,忽略优化级别集,-O0 除外,即 12 中的任何一个, 3s 即可。


这里有一些关于系统的附加信息:

$ /usr/bin/g++44 -v
    Using built-in specs.
    Target: x86_64-redhat-linux6E
    Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --disable-gnu-unique-object --with-as=/usr/libexec/binutils220/as --enable-languages=c,c++,fortran --disable-libgcj --with-mpfr=/builddir/build/BUILD/gcc-4.4.7-20120601/obj-x86_64-redhat-linux6E/mpfr-install/ --with-ppl=/builddir/build/BUILD/gcc-4.4.7-20120601/obj-x86_64-redhat-linux6E/ppl-install --with-cloog=/builddir/build/BUILD/gcc-4.4.7-20120601/obj-x86_64-redhat-linux6E/cloog-install --with-tune=generic --with-arch_32=i586 --build=x86_64-redhat-linux6E
    Thread model: posix
    gcc version 4.4.7 20120313 (Red Hat 4.4.7-1) (GCC)
$ cat /etc/redhat-release
    CentOS release 5.9 (Final)

最佳答案

带有 std::basic_string 的构造函数是在 C++ 标准 2011 中添加的。在此之前,此构造函数不存在。取而代之的是使用参数类型为 const char * 的构造函数。

关于c++ - GCC 4.4 fails to link valid C++11 code, when options are -std=C++0x -O0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20685874/

相关文章:

linux - 多进程同步 - 比信号量更好的选择?

c++ - std::is_trivially_copyable 太强了,我应该用什么来代替?

c++ - 为什么从 std::mem_fn 返回的可调用对象可以用于对象和 shared_ptr?

c++ - OpenCV - 使用带有 ORB 描述符的 FLANN 来匹配特征

linux - 限制用户使用操作系统级别的 ‘conn/as sysdba’

c++ - 一般处理文件流

linux - 将两行合并为一行并添加字符

c++ - 按值迭代的无序映射

c++ - 在 Visual C++ 中将图片从打开的文件对话框导入图片框

c++ - 尽管 "cin.get();"或系统 ("pause"控制台窗口不会停留在屏幕上)