-3

I have a simple program like:

int velocity=0;

#include "extra.h"

int main()
{
    extra();
    return 0;
}

where extra.h is:

void extra(){
   velocity += 1;
}

yet when I compile this, I get the error:

extra.h:5:5: error: 'velocity' was not declared in this scope

Obviously, my code in extra.h can't "see" the variables in main.c, but why is this? How do I fix this?

ikegami
  • 367,544
  • 15
  • 269
  • 518
Cerin
  • 60,957
  • 96
  • 316
  • 522

1 Answers1

0

You could add the following declaration to extra.h:

extern int velocity;

However, extra() shouldn't be defined in extra.h in the first place. This will cause problems if extra.h is included by multiple .c files in the same binary. The following is what you should have:

extra.h:

void extra();

extra.c:

#include "extra.h"

static int velocity = 0;

void extra() {
   velocity += 1;
}

main.c:

#include "extra.h"

int main()
{
    extra();
    return 0;
}
Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94
ikegami
  • 367,544
  • 15
  • 269
  • 518