c++ simple problem

How i declar a global variable,i have a project, a header file and 2 .cpp files, and if i declare in header : int x; there will be a error if i use this 'x' in the .cpp file.
i don't kno why, pls help
thks

ps. i am using visual studio 2008
Last edited on
If you declare it outside a function i think it will work
ok, explaining:

i have let say a project : head.h,fun.cpp,main.cpp

head.h
#ifndef _WHATEVER_
#define _WHATEVER_

int x;

#endif

fun.cpp
#include "head.h"

int getx()
{
return x;
}

main.cpp

#include <iostream>
#include "head.h"
using namespace std;

int main(void)
{
cin>>x;
cout<<x;

return 0;
}



THIS IS IT...what is wrong ?




Last edited on
1
2
//head.h
int x=5;


1
2
3
4
5
6
7
8
9
//main.cpp
#include <iostream>
#include <head.h>

int main()
{
std::cout<<x;
return 0;
}


This works perfectly with my compiler. I havent seen a construction with 2 cpp files before, i dont know or that causes problems (in this case, there is no link between those files), and i need to use <header.h> instead of "header.h".
Hoop this helps
try writing extern int x; in your header, then in one of the .cpp files define the x variable e.g. int x = 0; then it should work.

each variable in C++ needs to be both declared and defined. declarations can be done as many times as you like but there can be only one definition.
thanks anders43; its working now
@Scipio
Header files that you create yourself are #include-ed with doubled quotes around them instead of angle brackets.
Thanks for the information. I'm not very familiair with self-created header files. I was wondering wy i had to add the location :)
Topic archived. No new replies allowed.