Forcing Visual Studio to Only Use Explicitly Included Headers

Byeunggon KWAK 1 Reputation point
2021-01-05T07:31:29.43+00:00

In my project, below code still compiles without error despite not including <iterator> header.
I suspected it could compile because of precompiled headers, but when I checked the configuration properties, the configuration was set to not using precompiled headers.

I want to make Visual Studio to force me to include headers when I'm using functions from the header, but I can't find any way to do so.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int main() {
 std::cin.tie(nullptr);

 int cases;
 std::cin >> cases;

 std::vector<int> list;
 for (int i = 0; i < cases; ++i) {
 int input;
 std::cin >> input;
 list.push_back(input);
 }

 std::sort(list.begin(), list.end());
 std::copy(list.begin(), list.end(), std::ostream_iterator<int>(std::cout, "\n"));
 return 0;
}

This code doesn't compile with g++ (GCC) 10.2.0. with g++ Main.cc -o Main -O2 -Wall -lm -static -std=gnu++17.
The gcc compiler complains:

Main.cc: In function ‘int main()’:
Main.cc:20:43: error: ‘ostream_iterator’ is not a member of ‘std’
20 | std::copy(list.begin(), list.end(), std::ostream_iterator<int>(std::cout, "\n"));
| ^~~~~~~~~~~~~~~~
Main.cc:5:1: note: ‘std::ostream_iterator’ is defined in header ‘<iterator>’; did you forget to ‘#include <iterator>’?
4 | #include <algorithm>
+++ |+#include <iterator>
5 |
Main.cc:20:60: error: expected primary-expression before ‘int’
20 | std::copy(list.begin(), list.end(), std::ostream_iterator<int>(std::cout, "\n"));
| ^~~

Yet, on my Visual Studio project, the compiler doesn't.
I don't want to encounter further compiler errors on other machines, so I wish to know if Visual Studio can check that for me.

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,604 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,527 questions
{count} votes