0

I tried many solutions, but can't get my program work.

main.h

short NWMP_acc[3];
short NWMP_gyro[3];

main.cpp

printf_( "%i,%i,%i, g\n", NWMP_gyro[YAW],NWMP_gyro[PITCH],NWMP_gyro[ROLL]);

other.cpp

#include "main.h"
NWMP_gyro[YAW]   = (((buf[3]>>2)<<8) +  buffer[0]);//multiple definition of `NWMP_gyro'

If I change to "extern short NWMP_acc[3];" than I get an error "undefined reference to `NWMP_acc'"

2
  • 1
    printf_ looks like C not C++, but very odd C at that. Commented Jan 20, 2012 at 11:54
  • You want to declare the existence of global variables in the header, but you need to define them somewhere in just one source file. Commented Jan 20, 2012 at 11:54

2 Answers 2

6

You need both with and without the extern

In your header you need:

extern short NWMP_acc[3];
extern short NWMP_gyro[3];

But in one of your ".cpp" files you still need:

short NWMP_acc[3];
short NWMP_gyro[3];

The reason for this is that the extern keyword can be roughly thought of as meaning "I promise that somewhere in one file there exists an actual real thing that looks like this".

Sign up to request clarification or add additional context in comments.

4 Comments

Is this variables will be available to changing from other .cpp files?
@wsevendays: Yes, because it is declared as extern.
@wsevendays Yes, all of the other ones places which see the extern declaration will use the one single definition you provide, but you must provide exactly one definition somewhere still.
@wsevendays: Yes, it will be visible as long as you don't make the definition static, which of course you must not do when you really want a shared global variable.
4

If you declare the array as extern (which you have to if you want a global variable across translation units), you have to define it in exactly one translation unit. So, for example:

// main.h
extern short NWMP_acc[3]; // declare

// main.cpp
#include "main.h"
short NWMP_acc[3]; // define

// other.cpp    
#include "main.h"

void foo() {
    std::cout << NWMP_acc[0] << std::endl; //just use, don't define again
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.