cout is not a member of std
Asked Answered
Q

3

265

I'm practicing using mulitple files and header files etc. So I have this project which takes two numbers and then adds them. Pretty simple.

Here are my files:

main.cpp

#include <iostream>
#include "add.h"

int main()
{
    int x = readNumber();
    int y = readNumber();

    writeAnswer(x + y);

    return(0);
}

io.cpp

int readNumber()
{
    int x;

    std::cout << "Number: ";
    std::cin >> x;

    return x;
}

void writeAnswer(int x)
{
    std::cout << "Answer: ";
    std::cout << x;
}

add.h

#ifndef ADD_H_INCLUDED
#define ADD_H_INCLUDED

int readNumber();
void writeAnswer(int x);

#endif // #ifndef ADD_H_INCLUDED

The error is showing up in io.cpp. The exact errors are:

enter image description here

Does anyone have any idea why this may be happening? Thanks.

EDIT: I made a small project yesterday with the same amount of files (2 .cpp and 1.h) and I didn't include the iostream header in the other .cpp and it still compiled and ran fine.

Quip answered 7/7, 2012 at 14:43 Comment(3)
Re your edit: then you compiled that project differently. Including iostream in your second cpp file is required as you have it here. Maybe you had that include in the .h file last time around.Ahasuerus
Yeah, it's working great now, thanks for the quick responses everyone! :)Quip
always include system header files after your local files.Expostulatory
C
433

add #include <iostream> to the start of io.cpp too.

Clem answered 7/7, 2012 at 14:45 Comment(5)
iostream has to be included (directly or indirectly). Otherwise how would the compiler know where to find std::cout.Spotted
I understand what you're saying. Thanks. Though how did I get my other proj. to work without including it in the other .cpp too? I updated OP at the bottom.Quip
You´ve probably included it indirectly. It is ALWAYS required.Cardiogram
I needed to include it in a .h file as well!! ThanksContestation
also it has to be included after stdafx.h, not beforeStoker
C
27

If you're using pre-compiled headers with Microsoft's compiler (MSVC), remember that it must be:

#include "stdafx.h"
#include <iostream>

and not the other way around:

#include <iostream>
#include "stdafx.h"

In other words, the pre-compiled header include file must always come first. (The compiler should give you an error specifically explaining this if you forget.)

Counterscarp answered 20/9, 2018 at 19:41 Comment(0)
C
1

I had a similar issue and it turned out that i had to add an extra entry in cmake to include the files.

Since i was also using the zmq library I had to add this to the included libraries as well.

Crinkleroot answered 22/5, 2018 at 17:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.