0 c++ gcc mingw ifstream segmentation-fault
正如标题所示,我遇到了 ifstream 问题。我试图读取一个文本文件,在调试时可以正常工作,但在发布版本中则不行。我能够将范围缩小到下面的示例。
如果打开优化,以下代码在到达filein的声明时会出现段错误foo()。
#include <iostream>
#include <fstream>
void foo (){
std::cout << "I'm here 3" << std::endl;
std::ifstream file;
std::cout << "I'm here 4" << std::endl;
}
int main()
{
std::cout << "I'm here 1" << std::endl;
std::ifstream file;
std::cout << "I'm here 2" << std::endl;
foo();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
I'm here 1
I'm here 2
I'm here 3
Run Code Online (Sandbox Code Playgroud)
我正在使用以下命令进行编译和链接:
g++ -Wall -std=c++17 -O1 main.cpp -o main.exe
Run Code Online (Sandbox Code Playgroud)
如果我将其更改-O1为,O0它不会出现段错误并运行到最后。我不太确定问题是什么。
我的系统是 Windows 10,我正在运行g++.exe (x86_64-win32-seh-rev0, Built by MinGW-W64 project) 8.1.0. 这是编译器错误还是我只是做了一些愚蠢的事情?
既然--static修复了它,这意味着您的程序选择了不正确的 DLL 版本。
打开编译器的bin目录,并列出其中的所有 DLL。
然后:
(递归地)搜索这些 DLL C:\Windows。删除任何匹配的 DLL,它们不应该在那里。
确保你的编译器是 中的第一个目录PATH,或者至少它之前的任何目录不包含这些 DLL(或者更好的是,除了编译器目录之外的所有目录)。
这包括其中没有两个不同的 MinGW 版本PATH(或者您可以只卸载除一个之外的所有版本)。