1

Is it possible to declare something like an integer without defining it?

In C++, it is possible to separate the definition and declaration of a function.

// foo.cpp int foo(int); int foo(int a) { return 45; } 

But with a non-function it doesn't appear to be

// bar.cpp int bar; int bar = 10; 

bar.cpp produces this

$ clang++ -c bar.cpp bar.cpp:2:5: error: redefinition of 'a' int a = 10; ^ bar.cpp:1:5: note: previous definition is here int a; ^ 1 error generated. 

Leaving off the type annotation on the second statement produces a different error.

// bar2.cpp int bar; bar = 10; 

produces

$ clang++ -c bar2.cpp bar2.cpp:3:1: error: C++ requires a type specifier for all declarations bar = 10; ^ 1 error generated. 

1 Answer 1

7
extern int bar; // declares, but does not define bar int bar = 10; // defines bar 

Note that this requires bar to have static storage duration. Here's an example usage.

#include <iostream> int main() { extern int bar; std::cout << bar; // this should print 10 } int bar = 10; 
Sign up to request clarification or add additional context in comments.

1 Comment

I spend an extra five seconds testing to make sure it works, and someone else beats me to it!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.