How to make function local to main only?
Let us say i have
File1.c:
#include<stdio.h>
#include"File2.c"
void test(void)
{
sum(1,2);
}
int main(void)
{
int sum(int a,int b);
test();
sum(10,20);
return 0;
}
File2.c:
int sum(int x,int y)
{
printf("\nThe Sum is %d",x+y);
}
Now as far as my understanding goes test() calling sum() should give a Compile-Time Error since i have made/declared sum() local to main, which i am not getting, and the pr开发者_如何学Googram is running fine without any errors.
My main purpose is to define sum in File2.c and make it local to main() so that no other function has visibility to this function sum().
Where am i going wrong?
Mark the function as
static
(this makes it local to the current translation unit).For the love of god, do not include
.c
files! (read me)
Prototypes are helpful when compiling as they tell the compiler what a function's signature is. They are not a means of access control, though.
What you want to do is put sum()
into the same source file as main()
and give it static
linkage. Declaring it static
means it will only be available in that one .c
file, so functions in other source files will be unable to call it.
Then move test()
to another source file. That'll let main()
call test()
but not let test()
call sum()
since it's now in a different source file.
File1.c
#include <stdio.h>
/* NO! Do not #include source files. Only header files! */
/*** #include "File2.c" ***/
/* Prototypes to declare these functions. */
static int sum(int a, int b);
void test(void);
int main(void)
{
test();
sum(10, 20);
return 0;
}
/* "static" means this function is visible only in File1.c. No other .c file can
* call sum(). */
static int sum(int x, int y)
{
printf("\nThe Sum is %d", x + y);
}
File2.c
void test(void)
{
/* Error: sum() is not available here. */
sum(1, 2);
}
Notice, by the way, that I commented out the line #include "File2.c"
. You should never use #include
for .c
source files, only for .h
header files. Instead you will be compiling the two source files separately and then linking them together to make the final program.
How to do that depends on your compiler. If you're using an IDE like Visual C++ on Windows then add the two source files to a project and it will take care of linking them together. On Linux you'd compile them with something like:
$ gcc -o test File1.c File2.c
$ ./test
You have included File2.c in File1.c, so the sum function is defined in File1.c. Remove that line and things should work (you will have to #include <stdio.h>
in File2.c).
Note that most compilers will accept an implicit definition of the sum() function as used in test() unless they are in strict mode. For example, calling gcc File1.c File2.c
will succeed with no errors. If you want to see all the warnings available, call gcc -Wall -pedantic File1.c File2.c
which will warn you that sum is implicitly defined in test() and that your implementation of sum() doesn't return an int. Even then it will compile successfully and run.
精彩评论