簡體   English   中英

當選項為-std = C ++ 0x -O0時,GCC 4.4無法鏈接有效的C ++ 11代碼

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

這是根據第一個答案編輯的問題。 其他人向我指出,我認為無效的代碼在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的錯誤,但任何進一步的信息都很好。

關於同一問題有一個舊的線程 ,這使我成為-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 ,即任何的123s就行了。


以下是有關系統的其他信息:

$ /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)

那是因為代碼在C ++ 11中不是無效的。 C ++ 11中添加了一個以std::string作為第一個參數的構造函數 標志std=c++0x告訴g ++以C ++ 11模式(或您的版本支持的未來C ++ 11的任何子集)進行編譯

在C ++ 03中,您需要傳遞const char*

std::ofstream stream(name.c_str(), std::ofstream::trunc);

至於對優化級別的依賴,這很可能是您的安裝出現問題,或者是該特定版本的g ++中的真正錯誤。 不幸的是,我無法復制它。

在C ++ Standard 2011中添加了帶有std :: basic_string的構造函數。在此之前,此構造函數不存在。 取而代之的是使用參數類型為const char *的構造函數。

暫無
暫無

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

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