Domanda

I am trying to find some official confirmation on a theory with respect to C functions. In a simple project of mine, I have a function which I only want to be visible within the .c file in which it is defined. The function prototype is:

static int sum(int a, int b);

The function definition is:

int sum(int a, int b) {
   return (a+b);
}

Upon analysis of the build output, link maps, etc, it seems that the function is indeed static. I'm surprised that I don't get any build warnings or errors either. However, is there anything in terms of documentation (ie: specific line in the GCC manual) that can confirm this behavior, or what is expected?

I have found the equivalent of this question for C++ (Static keyword in function declaration can be missing in function definition?), but I am looking for the answer with respect to pure C.

Thank you.

È stato utile?

Soluzione

You can download the full specification from http://www.iso.org/iso/home/store/catalogue_ics/catalogue_detail_ics.htm?csnumber=57853

for 238 Swiss Francs, and I'm sure that will have the answer. Otherwise, the best source I have is from "The C Programming Language" 2nd edition by K&R, section 4.6 on page 83 (emphasis added)

"The external static declaration is most often used for variables, but it can be applied to functions as well. Normally, function names are global, visible to any part of the entire program. If a function is declared static, however, its name is invisible outside of the file in which it is declared."

Note that the quote only refers to the declaration of the function, not its definition, although it's common practice for static functions, that the definition serves as the declaration as well.

Altri suggerimenti

The function will be visible only in the .c by default, in order to make it visible to other files you would have to declare its prototype in the header ( .h file ).

Don't think of static here as in Java or other OO languages where only the class can call a static method, it is quite a difference.

The behaviour of static in C is that a function or variable is only known within the scope of the current compile, the data is kept in the executable file generated.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top