LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Why it doesn't compile? Linux g++ problem? or book error? (http://www.linuxquestions.org/questions/programming-9/why-it-doesnt-compile-linux-g-problem-or-book-error-462956/)

itz2000 07-11-2006 10:15 AM

Why it doesn't compile? Linux g++ problem? or book error?
 
Hey there.
I've done this simple code
Code:

#include <iostream>
using namespace std;


extern ostream* file;
int main() {
        *file << "hello world!" << endl;
        return 0;
}

why it doesn't compile? it gives me an error which says
Code:

[zuki@localhost C++]$ g++ zuki.cpp -o test
/home/zuki/tmp/cczkzetY.o: In function `main':
zuki.cpp:(.text+0x1d): undefined reference to `file'
collect2: ld returned 1 exit status

But I've copied the exact code from the book, so maybe it's a LINUX problem?

Thanks

cdhgee 07-11-2006 10:36 AM

This isn't a compilation problem, it's a linkage problem. You've declared file as an extern ostream*; the extern specifies that the actual declaration is defined elsewhere (probably in a library). The linker can't find the other reference to which the extern refers, hence the error.

You need to find out which library is required to compile this code snippet.

What's it supposed to do? There may be an easier way to do it.

itz2000 07-11-2006 10:38 AM

instead of writing it to the screen, I'd like to write that line to a file...

cdhgee 07-11-2006 10:41 AM

Try something like this:

Code:

#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Hello, world" << endl;
  myfile.close();
  return 0;
}



All times are GMT -5. The time now is 11:15 PM.