2017-05-10 2 views
-2

이 내 코드이러한 유형의 함수 프로토 타이핑이 오류를 던지는 이유는 무엇입니까?

#include<iostream> 
//#include<cmath> 
double sqrt(double); 

int main() 
{ 
    using namespace std; 

    cout << sqrt(16) << endl; 
    cin.get(); 

    return 0; 
} 

난 단지 C로 탐구하고 ++ 및 가정 [C++ 프라이머, 리프만] 함수 프로토 타입의 형태가 작동해야합니다. 내가 주석 라인 double sqrt(double); 를 교체 할 경우 내 코드가 작동 #include<cmath>

그러나 다른 방법이 오류 던져 않는 이유 : 라이브러리 함수의

$ g++ so_c++1_FntnPrototype.cpp -lm 
    /tmp/cc45Ec4F.o: In function `main': 
    so_c++1_FntnPrototype.cpp:(.text+0x22): undefined reference to `sqrt(double)' 
    collect2: error: ld returned 1 exit status 
+0

"sqrt에 대한 정의되지 않은 참조"를 웹 기반 검색 엔진에 붙여 넣은 것으로 생각하십니까? – juanchopanza

+1

'std :: sqrt'와'sqrt'는 다른 이름입니다. – BoBTFish

+0

@BoBTFish 여기서 중요한 것은 없다고 생각합니다. – juanchopanza

답변

0

수학 라이브러리 (-lm)의 함수에 C 링키지가있는 것이 문제입니다.

- (그래서 당신은 세부 사항에 대해 기억할 필요가 없습니다 헤더 파일이 사용되는 그 이유는 BTW.)

#include<iostream> 

extern "C" double sqrt(double); 

int main() 
{ 
    using namespace std; 

    cout << sqrt(16) << endl; 
    cin.get(); 

    return 0; 
} 

을 : 당신이 sqrt 프로토 타입을 수정하면 좋은 프로그램 링크는 C 결합을해야 함을 표시합니다

+0

감사합니다. 가장 좋은 대답입니다. – Sharan

1

이름이 예약되어 있습니다. C++ 14 [extern.names]/3 :

If a program declares or defines a name in a context where it is reserved, other than as explicitly allowed by this Clause, its behavior is undefined.

Undefined behaviour 아무것도 일어날 수 있다는 것을 의미한다 :

Each name from the Standard C library declared with external linkage is reserved to the implementation for use as a name with extern "C" linkage, both in namespace std and in the global namespace.

Each function signature from the Standard C library declared with external linkage is reserved to the implementation for use as a function signature with both extern "C" and extern "C++" linkage, or as a name of namespace scope in the global namespace.

이 구현에 예약 되는 이름을 선언하려고하면 그것은 정의되지 않은 동작이 것을 의미 ; 이 경우에는 컴파일에 실패한 코드가 포함됩니다.

+0

나는 그것이 실제로 어떻게 대답하는지 * 모른다. –

+0

@ el.pescado 정의되지 않은 동작은 아무 일도 일어나지 않는다는 것을 의미합니다 (이 경우 컴파일 오류 포함). –

+0

4 번 읽은 후 이해가 시작되지만 여전히 배우기 시작한 사람이 이해하기가 어렵다고 생각합니다. C++. –

관련 문제