How to make a local function only basic!

Let's 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 I understand it, the test () call to sum () should give a compile-time error, since I made / declared sum () local main, which I do not get, and the program works fine without any errors.

My main goal is to define the sum in File2.c and make it local to main () so that no other function has visibility for this sum () function.

Where am I mistaken?

+3
source share
3 answers

Prototypes are useful when compiling when they tell the compiler what a function signature is. However, they are not a means of access control.

, sum() , main(), static. static , .c , .

test() . main() test(), test() sum(), .

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);
}

, #include "File2.c". #include .c , .h. , , .

, . IDE, Visual ++, Windows, , . Linux - :

$ gcc -o test File1.c File2.c
$ ./test
+4
  • static ( ).

  • .c! ( )

+7

File2.c File1.c, sum File1.c. , ( #include <stdio.h> File2.c).

Note that most compilers will accept the implicit definition of the sum () function used in test () if they are not in strict mode. For example, a call gcc File1.c File2.cwill succeed without errors. If you want to view all available warnings, call gcc -Wall -pedantic File1.c File2.cthat will warn you that the amount is implicitly defined in test () and that your implementation of sum () does not return int. Even then, it will compile and run successfully.

+1
source

Source: https://habr.com/ru/post/1763334/


All Articles