I
Immortal_Nephi
I always write global variables and global functions on all modules.
I find a way how to encapsulate global variable and global function.
I place static on Modify() function and it becomes internal linkage
in file scope -- Color.h & Color.c. How do I place static on global
variable Red? Should I place static in header -- Color.h or source
code -- Color.c?
main() function is not supposed to modify Red outside of file scope
-- Color.h & Color.c. Red and Modify() are hidden. Why can't C
Compiler fail to report saying Red should be static.
Global variable and global function in file scope are ideal to be
written into static library or dynamic linked library file so main()
can reuse them. Can you please make correction for me in my example
code below.
/* Color.h */
#ifndef COLOR_H
#define COLOR_H
static int Red = 10;
extern int Green;
extern int Blue;
void Print();
static void Modify();
#endif // COLOR_H
#include "Color.h"
/* Color.c */
int Green = 20;
int Blue = 30;
void Print()
{
Modify();
}
void Modify()
{
Red += 10;
}
/* main.c */
#include "Color.h"
int main(void)
{
Red += 50; /* main() should not access Red because Red is internal
linkage. How can C Compiler fails to compile? */
Green += 100;
Blue += 200;
Print();
Modify(); / C Compiler failed to compile --Correct */
return 0;
}
Nephi
I find a way how to encapsulate global variable and global function.
I place static on Modify() function and it becomes internal linkage
in file scope -- Color.h & Color.c. How do I place static on global
variable Red? Should I place static in header -- Color.h or source
code -- Color.c?
main() function is not supposed to modify Red outside of file scope
-- Color.h & Color.c. Red and Modify() are hidden. Why can't C
Compiler fail to report saying Red should be static.
Global variable and global function in file scope are ideal to be
written into static library or dynamic linked library file so main()
can reuse them. Can you please make correction for me in my example
code below.
/* Color.h */
#ifndef COLOR_H
#define COLOR_H
static int Red = 10;
extern int Green;
extern int Blue;
void Print();
static void Modify();
#endif // COLOR_H
#include "Color.h"
/* Color.c */
int Green = 20;
int Blue = 30;
void Print()
{
Modify();
}
void Modify()
{
Red += 10;
}
/* main.c */
#include "Color.h"
int main(void)
{
Red += 50; /* main() should not access Red because Red is internal
linkage. How can C Compiler fails to compile? */
Green += 100;
Blue += 200;
Print();
Modify(); / C Compiler failed to compile --Correct */
return 0;
}
Nephi