Weird includes

So, I'm using Visual Studio and I'm coding a Tetris game with SFML. Everything's going well, but I've run into a bit of weirdness. If I #include <iostream> in main.cpp, for example, I can use iostream in all the headers that main includes.

1
2
3
4
5
6
7
8
9
//main.cpp
#include <iostream>
#include "MyClass.h"

int main()
{
    MyClass object;
    object.saySomething();
}



1
2
3
4
5
6
7
//MyClass.h
#pragma once

class myClass
{
    void saySomething();
};


1
2
3
4
5
6
7
8
//MyClass.cpp
#include "MyClass.h"

void MyClass::saySomething()
{
    //This works because iostream is included in main.cpp
    std::cout << "Something\n";
}


After reading http://www.cplusplus.com/forum/articles/10627/ again, that seems to just be how #include works, which I must have missed at some point. My issue is that it can be confusing when a file depends on another that has already been included. I'll be typing out a class and suddenly need iostream, for example. By habit, I just start using cout and it works even though I didn't include iostream in that file. Obviously, that's no good since I'd HAVE to include iostream elsewhere or MyClass won't work. Is there any way to prevent this? Obviously remembering to explicitly include whatever is needed is the first step, but if I do forget, I don't want it to go unnoticed.
you can just include everything you need again.
The compiler should minimize it anyways
Oh, I know. I don't have a problem with that. I have a problem with the fact that I'm allowed to use files that haven't been included in the file I'm working with just because they've been included elsewhere.

Consider the following:
- main.cpp includes iostream.
- MyClass.h DOESN'T include iostream.
- MyClass.cpp uses std::cout.

Now, if I want to reuse MyClass in another project, it won't compile because I forgot to include iostream. However, I wouldn't notice the problem in the first program because I included it in main.cpp.

Basically, the problem is that I don't want to have to go back to fix a mistake that simple when it could have been avoided in the first place.
Last edited on
#include is a preprocessor statement. Before the compiler even gets to look at your code, your files get run through C's preprocessor. An #include gets replaced by the literal contents of the specified file. At the end of the day your compiler doesn't actually know about header files, it just pretends to. In reality there are only source files with thousands of lines of code from includes.
Last edited on
Topic archived. No new replies allowed.