473,671 Members | 2,311 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to protect a global variable in a header file from external access? ("static int i" does not work!)

Lu
Hello, I am wondering how to protect a global variable in a header file from
external access. So I googled and found:

"The keyword 'static' has two different uses, depending on whether it is
applied to an external variable or function or to an automatic variable.
When applied to an external variable (global) variable the scope of that
variable to the file in which it is declared. This is useful to hide buffers
and variables that are used only by functions in a particular file."

However, when I tried to teach my self and do the following exercise, it
shows me that static global variables are still available in "main.c".

[jxlu@edusrv jxlu]$ cat static_i.c
#include <stdio.h>
#include "static_i.h "

int main(int argc,char *argv[])
{
printf("i=%d\n" ,i);
return 0;
}
[jxlu@edusrv jxlu]$ cat static_i.h
static int i=0;
[jxlu@edusrv jxlu]$ gcc -Wall -o static_i static_i.c
[jxlu@edusrv jxlu]$ ./static_i
i=0
[jxlu@edusrv jxlu]$

It really puzzles me! Any suggestions?

Sincerely,
Lu


Nov 13 '05 #1
2 9078
On Tue, 8 Jul 2003 11:06:45 +0800, Lu <jx**@fudan.edu .cn> wrote:
[jxlu@edusrv jxlu]$ cat static_i.c
#include <stdio.h>
#include "static_i.h "

int main(int argc,char *argv[])
{
printf("i=%d\n" ,i);
return 0;
}
[jxlu@edusrv jxlu]$ cat static_i.h
static int i=0;
[jxlu@edusrv jxlu]$ gcc -Wall -o static_i static_i.c
[jxlu@edusrv jxlu]$ ./static_i
i=0
[jxlu@edusrv jxlu]$


Your problem is, in part, a misunderstandin g of how headers work. When
you say:
#include "static_i.h "

all you're doing is, in essence, copying and pasting static_i.h into
whatever file is including it. So your static_i.c actually starts off
like:
#include <stdio.h>
static int i=0;
....

static_i.c is getting its own copy of i. Any file that includes
static_i.h gets its own copy of i, because you will have essentially
typed "static int i;" into each source file.

First, let me tell you not to put definitions in header files. In this
case it actually works (as in, compiles), but unless you have some real
need for each source file to have its own object named "i", it's not
good style (and even then I'd argue it's not good style).

Here's how you can see static in action:
$ cat > i.c
static int i;
^D
$ cat > main.c
/* Here's the important part: you're telling main.c that someone else
* has defined an object named "i" and you want to use that object.
* Hopefully the static-ness of "i" won't let this happen.
*/
extern int i;

int main(void)
{
i = 0;
return 0;
}
^D
$ cc main.c i.c
/tmp/cc0Iyqp6.o: In function `main':
/tmp/cc0Iyqp6.o(.tex t+0x12): undefined reference to `i'

So as you see, main.c wasn't able to find "i", as was expected.

When you're trying to give stuff internal linkage, it doesn't make sense
to do it in headers; headers are included in various source files, but
objects/functions with internal linkage are tied, necessarily, to one
source file.

Chris
Nov 13 '05 #2
On Tue, 8 Jul 2003 11:06:45 +0800, in comp.lang.c , "Lu"
<jx**@fudan.edu .cn> wrote:
Hello, I am wondering how to protect a global variable in a header file from
external access.


You can't. A variable in a header file is accessible in every source
file which includes that variable.

You do it the other way round. Declare the variable as static in one
file, and write accessor functions to read the data. Put the accessor
declarations in some header.

static int x;
int getx(){ return x;}
int setx(int v) { int tmp = x; x = v; return tmp;}

and so forth.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
742
by: Nobody | last post by:
Hi All, In my application I have the following implementation for ClassA and ClassC invoking a call on ClassB. void ClassA::DoSomething() { int value = m_pClassB->Read(enum1); }
2
5182
by: Bryan Parkoff | last post by:
….I would like to know which is the best optimization to use global variable or global struct. I always tell C/C++ Compiler to turn on optimization. ….I use underscore between first name and second name for better readable. After optimization, global variables might be misaligned because each global variables must be converted to 32 bits, but I do see that C/C++ Compiler do padding between variables. Struct does the same to do padding....
4
7116
by: Dan Elliott | last post by:
Hello, Converting from a working C program to C++, I run into the following error: I have a header: (header.h) namespace shared{ ... struct X{ ...
0
1825
by: beanweed | last post by:
BACKGROUND ---------- I have an ASP.NET application having two panels. In one panel, an XML document, transformed using xsl, is displayed. In the other panel are some controls that allow a user to change the xml. For example, each "l_item" element appears as a row in a table labelled with a "label"; so if I have <l_item id="1"> <label>blah</label> ...
6
1736
by: candy | last post by:
hi all, I just want to know that whether the C header files( like stdio.h,etc which the compiler provides) just contains the function declarations or they also contain some additionalinformation like where to look in the memory for the defintions of the standard functions like scanf(char*c,...)).
0
1550
by: gilad | last post by:
If you have a C/C++ source that defines a global variable and compiles as a DLL, what are the ramifications when the exported functions are called from a language like C#, especially in regard to threading? For instance, let's say I have a C DLL source like that below: // Global structure declared my_global_struct my_gstruct;
4
1672
by: C_Programmer | last post by:
Question#1: ========== ========== What is the default value for any Static Global variable? Example: A.c: =====
2
1774
by: yoavip | last post by:
Hi, I'm using VC++ 6.0, and I have the following problem: when I change a header file, and compile, the compiler does not recognize the change, and does not compile the files that use this header file. This only happen in one specific project, and not in other projects. Did anyone saw this problem before ?
9
356
by: Shilpa | last post by:
Hi, I just wanted to know whether we can access global variable within a local block , where both variables are having same name. For ex: int temp=5 ; { int temp=10;
0
8390
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8819
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8597
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8667
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7428
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6222
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4222
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4402
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.