Tuesday, March 1, 2011

Can you declare a pointer as extern in C++?

I have the following bit of legacy C++ code that does not compile:

#include <stdio.h>
#include <iostream>

extern ostream *debug;

GCC (g++) complains: "expected initializer before ‘*’ token"

Looking around it seems more common to declare these as external references, like this:

extern ostream& debug;

Why is a pointer not valid, but a reference is in this situation?

SOLUTION:

The real problem, as mentioned below is that the std:: namespace specifier is missing. Apparently, this was common in older C++ code.

From stackoverflow
  • Yes, you can declare a pointer using extern. Your error is most likely you forgot to qualify using std:: :

    // note the header is cstdio in C++. stdio.h is deprecated
    #include <cstdio>
    #include <iostream>
    
    extern std::ostream *debug;
    
    postfuturist : Ah yes, namespaces were not always necessary for standard C++ libraries.
    Johannes Schaub - litb : yes. those were the time before C++ became a standard. you used to include iostream.h , and use ostream without qualifying it. but nowadays, c++ is a standard, and it requires you to use std:: :)

0 comments:

Post a Comment