#include <iostream>
int ReadNumber()
{
usingnamespace std;
cout << "Enter a number: ";
int x;
cin >> x;
return x;
}
void WriteAnswer(int x)
{
usingnamespace std;
cout << "The answer is " << x << endl;
}
int main()
{
int x = ReadNumber();
int y = ReadNumber();
WriteAnswer(x+y);
return 0;
}
Here is the error it gives me:
~/Desktop/c++learning/quiz1> gcc -o num1 num1.cpp
/tmp/ccmz5SRA.o: In function `ReadNumber(void)':
num1.cpp:(.text+0x21): undefined reference to `cout'
num1.cpp:(.text+0x29): undefined reference to `ostream::operator<<(char const *)'
num1.cpp:(.text+0x39): undefined reference to `cin'
num1.cpp:(.text+0x41): undefined reference to `istream::operator>>(int &)'
/tmp/ccmz5SRA.o: In function `WriteAnswer(int)':
num1.cpp:(.text+0x70): undefined reference to `endl(ostream &)'
num1.cpp:(.text+0x8c): undefined reference to `cout'
num1.cpp:(.text+0x94): undefined reference to `ostream::operator<<(char const *)'
num1.cpp:(.text+0x9f): undefined reference to `ostream::operator<<(int)'
collect2: ld returned 1 exit status
if I use cout in the main method it doesn't give me errors, but if I use it in a different method it does. I am using gcc on Haiku OS.
That's weird. Did you try putting usingnamespace std; just under #include <iostream> ? Did you also try doing std::cout and std::cin? And what about doing using std::cin; and using std::cout;? But, really, that code should compile.
#include <iostream>
usingnamespace std;
int ReadNumber()
{
cout << "Enter a number: ";
int x;
cin >> x;
return x;
}
void WriteAnswer(int x)
{
cout << "The answer is " << x << endl;
}
int main()
{
int x = ReadNumber();
int y = ReadNumber();
WriteAnswer(x+y);
cin.get();
return 0;
}
Thanks for all your help. I posted in the haiku forums and someone told me I was trying to use the c compiler, not the c++ compiler. I should use the g++ command instead of the gcc command.