低版本GCC程序向高版本移植的兼容性問題


將低版本gcc編譯過的程序移植到高版本GCC時, 可能會出現一些兼容性問題. 原因是, 為了適應新的標准,一些舊的語法規則被廢棄了. 關於這方面的一些具體資料可從該處查詢. 這里只是自己遇到的其中一個問題.

錯誤提示:

In instantiation of ‘int t(T) [with T = int]’
  required from here
  error: ‘f’ was not declared in this scope, and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive]
  note: ‘int f(int)’ declared here, later in the translation unit

錯誤原因:

 The C++ compiler no longer performs some extra unqualified lookups it had performed in the past, namely dependent base class scope lookups and unqualified template function lookups.

C++ programs that depended on the compiler's previous behavior may no longer compile. For example, code such as

//foo1.cpp
template<typename T> int t(T i) { return f(i); } int f(int i) { return i; } int main() { return t(1); }

解決方法:

To fix, make sure the function f in the code above is declared before first use in function t. Like so:

//foo2.cpp
int
f(int i) { return i; } template<typename T> int t(T i) { return f(i); } int main() { return t(1); }

意思是說, C++編譯器不再支持那種非標准的模板類中函數查找方式,如foo1.cpp所示, 在定義模板類時使用的函數在該模板類之前未定義, 而是在該模板類之后定義. 早期的C++編譯器支持向后查找. 但是新標准出來后, 該方式被廢除了. 因此會報錯. 如foo2.cpp所示, 在模板類中使用某個函數之前應先對該函數進行定義. 這才是正確的姿勢.

 Or this can be temporarily worked around by using -fpermissive.

第一種方法方法可以從根本上解決問題, 但是有情況是我們編譯別人的程序, 並且程序十分復雜, 不是我們可以輕易改變的. 這時有個臨時性的方法, 那便是在編譯時添加 -fpermissive 選項. 我自己的項目是利用Cmake進行構建的, 因此只需要在 CmakeList.txt 文件中添加一行: ADD_DEFINITIONS(-fpermissive), 然后重新 cmake 一下即可. 此時將錯誤降為警告, 可順利通過編譯.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM