Results 1 to 5 of 5

Thread: Global variable declare

  1. #1

    Thread Starter
    PowerPoster Chris's Avatar
    Join Date
    Jan 1999
    Location
    K-PAX
    Posts
    3,238

    Smile

    How can I declare a public variable in C++ (without MFC) and so that I can share this variable in two different cpp file.

    example:
    I have 2 variable name ptX and ptY both are double data type.
    I need to store a value at runtime into this variable at a.cpp and use this value in b.cpp.

    Thanks,
    Chris.C


  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    Your variable is declared as normal in the first .cpp file. In the second, add an extern definition. For example:

    file1.cpp
    Code:
    int iVar;
    file2.cpp
    Code:
    extern int iVar;
    Make sense? (I hope so! )
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  3. #3

    Thread Starter
    PowerPoster Chris's Avatar
    Join Date
    Jan 1999
    Location
    K-PAX
    Posts
    3,238
    can I do it in this way?
    Code:
    file1.h
    double   pt1;
    Code:
    file2.cpp
    extern double   pt1;

  4. #4
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    If file2.cpp includes file1.h, then you don't need to do anything in file2.cpp, since it will have it. However, it's not usually a good idea to declare variables in a header. Unless, of course, it's an extern. In <iostream>, there is a definition of:
    Code:
    extern ... cout;
    ...because it refers to one thing all the way through all the code. Normally headers should only contain definitions of classes, types, structures, and as little code as possible. (You can put code in, but be careful)
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  5. #5

    Thread Starter
    PowerPoster Chris's Avatar
    Join Date
    Jan 1999
    Location
    K-PAX
    Posts
    3,238

    Thumbs up

    Thanks Parksie. I know how to improve my program already. Thanks a lot for your explaination.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width