2017-05-10 9 views
-2

は、これは私のコードこのタイプの関数プロトタイプがエラーを投げるのはなぜですか?

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

int main() 
{ 
    using namespace std; 

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

    return 0; 
} 

私はCのみに模索しています++およびおそらく[C++入門、リップマン]機能プロトタイピングのこのフォームが動作しなければならないです。ライブラリ関数の

$ 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への未定義の参照"をWebベースの検索エンジンに貼り付けることを検討しましたか? – juanchopanza

+1

'std :: sqrt'と' sqrt'は異なる名前です。 – BoBTFish

+0

@BoBTFish私はここで重要だとは思わない。 – juanchopanza

答えて

0

問題は、数学ライブラリ(-lm)の関数にCリンケージがあることです。 -

#include<iostream> 

extern "C" double sqrt(double); 

int main() 
{ 
    using namespace std; 

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

    return 0; 
} 

(。あなたは、このような詳細を覚えておく必要はありませんBTWヘッダファイルが使用されている理由です):あなたはsqrtそれがCリンケージを持つべきであることを示すためのプロトタイプ、あなたのプログラムのリンク罰金を変更した場合

+0

ありがとうございます。最高の答え。 – Sharan

1

名に予約されています:私はコメント行#include<cmath>

double sqrt(double); を置き換えるしかし、なぜ他の方法は、このエラーをスローしない場合 私のコードは動作します。 C++ 14 [extern.names]/3:

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.

が実装に予約されているが、あなたが名前を宣言しようとした場合、それは未定義の動作だということを意味します

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は何が起こることができることを意味し;この場合、コンパイルに失敗したコードが含まれています。

+0

実際にどう答えているのか分かりません。 –

+0

@ el.pescado未定義の動作は、何かが起こる可能性があることを意味します(この場合はコンパイルエラーを含みます)。 –

+0

4回読むと理解し始めますが、 C++。 –