declaring a variable

i am a little confused with the difference between declaring & defining a variable and a function
int x; is supposed to be defining a variable whereas extern int x; is considered to be declaring a variable.i am not able to get the logic.
Also can anyone give me a proper explanation of use of extern with variables and functions...As far as i know extern is added implicitely by the compiler to any function declaration.Dows it mean that that a function declared in 1 file can be accessed in other file????but this doesnt seem to work out for me
The extern keyword declares a variable or function and specifies that it has external linkage (its name is visible from files other than the one in which it's defined).

http://msdn.microsoft.com/en-us/library/0603949d(v=vs.80).aspx
To access functions in another file you need something like this:

myFunctions.h
1
2
3
4
5
6
#ifndef MYFUNCTIONS_H
#define MYFUNCTIONS_H

int add(int x, int y);

#endif 


myFunctions.cpp
1
2
3
4
5
6
#include "myFunctions.h"

int add(int x, int y)
{
  return x + y;
}


main.cpp
1
2
3
4
5
6
7
8
#include <iostream>
#include "myFunctions.h"

int main(void)
{
  std::cout << "1 + 2 = " << add(1,2) << std::endl;
  return 0;
}

You're question about variables:

declaring a variable tells the compiler (or w/e you're using) what type the variable will be (int, char, double etc.) and that you will be using this variable later on in the program.

Defining a variable just tells the compiler what the variable is equal to.

an example of both would be:
Declaring - int x
Defining - x=5

Both at the same time - int x = 5
Topic archived. No new replies allowed.