【发布时间】:2013-12-19 15:45:39
【问题描述】:
这是一个基于第一个答案的编辑问题。其他人向我指出,我认为无效的代码在 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 除外,即1、2、3、s 中的任何一个都可以。
以下是有关系统的一些附加信息:
$ /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)
【问题讨论】:
-
gcc 4.4 是古老的,它的 c++0x 模式肯定在许多层面上都被破坏/不完整。
-
@PlasmaHH,很遗憾,我无法切换 gcc 版本