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