[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: g++ and Static Variables
From: |
Larry I Smith |
Subject: |
Re: g++ and Static Variables |
Date: |
Mon, 02 May 2005 15:53:26 GMT |
User-agent: |
Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.7) Gecko/20050414 |
fewgoodmen@gmail.com wrote:
> I am currently working on changing the compiler from Sun Workshop to
> g++ for a mid sized C program. In the C files we have static variables
> defined and declared. This works fine with the Sun Workshop compiler.
> However under g++ the static variables are initialized to zero but do
> not have the value they are assigned to. For example say file2.cc I
> have static variable defined and declared as
> static int j = 5;
> Variable j seems to have a value of zero and not 5. However any static
> variables defined and declared in the file that contains function main
> seems to have the value that is assigned to them. I am using g++
> version 3.2.2 in a Solaris 8 environment.
> Any help would be appreciated.
>
> Joe
>
Assuming your program is really C++, here's a trivial example
comprised of 2 files, xx.cc and xx1.cc:
------- xx1.cc ------
// 'ej' can be globally visible if
// declared as 'extern int ej' in other
// source files or headers.
int ej = 8;
------- xx.cc -------
#include <iostream>
// because of the 'static' keyword, 'j' is visible
// only within THIS source file. this applies to both
// 'C' and 'C++'
static int j = 5;
// declare that 'ej' resides in another file.
// this statement could also be in a header file
// that is included by all source files needing
// access to 'ej'
extern int ej;
int main()
{
std::cout << " j is: " << j << std::endl;
std::cout << "ej is: " << ej << std::endl;
return 0;
}
compile the above 2 files with:
g++ -o xx xx.cc xx1.cc
execute the compiled example with:
./xx
Regards,
Larry
--
Anti-spam address, change each 'X' to '.' to reply directly.