UFO ET IT

함수 프로토 타입을 C로 선언해야합니까?

ufoet 2021. 1. 17. 11:37
반응형

함수 프로토 타입을 C로 선언해야합니까?


이 질문에 이미 답변이 있습니다.

저는 C에 익숙하지 않습니다 (이전 Java, C # 및 일부 C ++ 경험이 있습니다). C에서 함수 프로토 타입을 선언해야합니까? 아니면 코드 없이도 코드를 컴파일 할 수 있습니까? 그렇게하는 것이 좋은 프로그래밍 관행입니까? 아니면 컴파일러에 의존합니까? (우분투 9.10을 실행 중이며 Code :: Blocks IDE에서 GNU C 컴파일러 또는 gcc를 사용하고 있습니다)


ANSI C (C89 또는 C90 의미)에서는 함수 프로토 타입을 선언 할 필요가 없습니다. 그러나이를 사용하는 것이 가장 좋습니다. 표준에서 사용하지 않는 유일한 이유는 매우 오래된 코드와의 하위 호환성 때문입니다.

프로토 타입이없고 함수를 호출하면 컴파일러는 함수에 전달하는 매개 변수에서 프로토 타입을 유추합니다. 나중에 동일한 컴파일 단위에서 함수를 선언하면 함수의 서명이 컴파일러가 추측 한 것과 다른 경우 컴파일 오류가 발생합니다.

더 나쁜 것은 함수가 다른 컴파일 유닛에 있다면, 프로토 타입이 없으면 확인할 방법이 없기 때문에 컴파일 오류가 발생할 방법이 없습니다. 이 경우 컴파일러가 잘못 인식하면 함수 호출이 함수가 예상하는 것과 다른 유형을 스택에 푸시하면 정의되지 않은 동작이 발생할 수 있습니다.

규칙은 항상 함수를 포함하는 소스 파일과 이름이 같은 헤더 파일에서 프로토 타입을 선언하는 것입니다.

C99 또는 C11에서 표준 C는 함수를 호출하기 전에 범위에서 함수 선언이 필요합니다. 많은 컴파일러는 강제로 실행하지 않는 한 실제로이 제한을 적용하지 않습니다.


"이전"C (C89 / 90 포함) 나 새 C (C99)가 아닌 C에서 함수에 대한 프로토 타입 을 선언 할 필요가 없습니다 . 그러나 함수 선언과 관련하여 C89 / 90과 C99에는 상당한 차이가 있습니다.

C89 / 90에서는 함수를 선언 할 필요가 전혀 없습니다. 함수가 호출 지점에서 선언되지 않은 경우 컴파일러는 호출에서 전달 된 인수의 유형에서 암시 적으로 선언을 "추측"(취소)하고 반환 유형이라고 가정합니다 int.

예를 들면

int main() {
  int i = foo(5); 
  /* No declaration for `foo`, no prototype for `foo`.
     Will work in C89/90. Assumes `int foo(int)` */

  return 0;
}

int foo(int i) {
  return i;
}

C99에서 호출하는 모든 함수는 호출 지점 이전에 선언 되어야합니다 . 그러나 아직 프로토 타입을 사용하여 구체적 으로 선언 할 필요는 없습니다 . 프로토 타입이 아닌 선언도 작동합니다. 즉, C99에서는 "암시 적 int"규칙이 더 이상 작동하지 않지만 (이 경우 유추 된 함수 반환 유형의 경우) 함수가 프로토 타입없이 선언 된 경우 인수 유형에서 매개 변수 유형을 추측 할 수 있습니다.

이전 예제는 foo호출 지점에서 선언되지 않았으므로 C99에서 컴파일 되지 않습니다. 그러나 프로토 타입이 아닌 선언을 추가 할 수 있습니다.

int foo(); /* Declares `foo`, but still no prototype */

int main() {
  int i = foo(5); 
  /* No prototype for `foo`, although return type is known. 
     Will work in C99. Assumes `int foo(int)` */

  return 0;
}
...

유효한 C99 코드로 끝납니다.

그럼에도 불구하고 함수를 호출하기 전에 항상 프로토 타입을 선언하는 것이 좋습니다.

추가 참고 사항 : 함수 프로토 타입을 선언 할 필요가 없다고 위에서 언급했습니다. 실제로 일부 기능의 경우 필수 사항입니다. C ( :) 에서 가변 함수 를 올바르게 호출하려면 호출 지점 전에 프로토 타입을 사용printf 하여 함수를 선언해야합니다 . 그렇지 않으면 동작이 정의되지 않습니다. 이는 C89 / 90 및 C99 모두에 적용됩니다.


함수가 사용되기 전에 정의 된 경우 필수가 아닙니다.


필수는 아니지만 프로토 타입을 사용하지 않는 것은 좋지 않습니다.

프로토 타입을 사용하면 컴파일러는 올바른 수와 유형의 매개 변수를 사용하여 함수를 올바르게 호출하고 있는지 확인할 수 있습니다.

프로토 타입이 없으면 다음과 같이 할 수 있습니다.

// file1.c
void doit(double d)
{
    ....
}

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

이:

// file2.c

// In C, this is just a declaration and not a prototype
void doit();
int sum();

int main(int argc, char *argv[])
{
    char idea[] = "use prototypes!";

    // without the prototype, the compiler will pass a char *
    // to a function that expects a double
    doit(idea);

    // and here without a prototype the compiler allows you to
    // call a function that is expecting three argument with just
    // one argument (in the calling function, args b and c will be
    // random junk)
    return sum(argc);
}

In C, if we do not declare a function prototype and use the function definition, there is no problem and the program compiles and generates the output if the return type of the function is "integer". In all other conditions the compiler error appears. The reason is, if we call a function and do not declare a function prototype then the compiler generates a prototype which returns an integer and it searches for the similar function definition. if the function prototype matches then it compiles successfully. If the return type is not integer then the function prototypes do not match and it generates an error. So it is better to declare function prototype in the header files.


C allows functions to be called even though they have not previously been declared, but I strongly recommend you to declare a prototype for all functions before using them so that the compiler can save you if you use the wrong arguments.


You should put function declarations in the header file (X.h) and the definition in the source file (X.c). Then other files can #include "X.h" and call the function.


Function prototype is not mandatory according to the C99 standard.


It's not absolutely necessary to declare a function for the calling code to compile. There are caveats though. Undeclared function is assumed to return int and compiler will issue warnings first about function being undeclared and then about any mismatches in return type and parameter types.

Having said that it's obvious that declaring functions properly with prototypes is a much better practice.


Select ‘Options’ menu and then select ‘Compiler | C++ Options’. In the dialog box that pops up, select ‘CPP always’ in the ‘Use C++ Compiler’ options. Again select ‘Options’ menu and then select ‘Environment | Editor’. Make sure that the default extension is ‘C’ rather than ‘CPP’.

ReferenceURL : https://stackoverflow.com/questions/2575153/must-declare-function-prototype-in-c

반응형