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 program 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?
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 asmain()and give itstaticlinkage. Declaring itstaticmeans it will only be available in that one.cfile, so functions in other source files will be unable to call it.Then move
test()to another source file. That’ll letmain()calltest()but not lettest()callsum()since it’s now in a different source file.File1.c
File2.c
Notice, by the way, that I commented out the line
#include "File2.c". You should never use#includefor.csource files, only for.hheader 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: