Ian Woodley
Ian Woodley

Reputation: 85

Why do these headers only work outside of the pre-compiled header?

In stdafx.h:

#include <fstream>
#include <sstream>

In example.cpp:

#include <stdafx.h>
std::ifstream in_stream;
std::stringstream st_stream;

If I don't place the fstream and sstream includes in the .cpp file I get a ton of errors, such as:

Error   C2079   'in_stream' uses undefined class 
'std::basic_ifstream<char,std::char_traits<char>>'

Error   C2228   left of '.exceptions' must have class/struct/union  

Why do the errors disappear if I place the appropriate includes directly in the .cpp file? Shouldn't the functionality be identical?

Upvotes: 0

Views: 124

Answers (1)

Barmak Shemirani
Barmak Shemirani

Reputation: 31609

This should be written as "stdafx.h" not <stdafx.h>, because "stdafx.h" is not a standard header file (that's just C++ ethics, not rules).

Visual Studio automatically creates this files and adds a bunch of header files to it.

If you have a large project with many source files, and <fstream> is used in many source files, then include <fstream> in "stdafx.h". Otherwise avoid editing this file.

std::ifstream requires <fstream> header files. The required header file is mentioned in relevant help pages. See for example std::ifstream help

Add the relevant header files directly in your "myfile.cpp" file:

//myfile.cpp:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
int main(){...}

If you have a small project you can tell Visual Studio to stop using precompiled headers via "Project Settings" -> "C/C++" -> "Precompiled Headers". This way you can remove "stdafx.h" and your source file will be more compatible with different compilers.

Upvotes: 1

Related Questions