2016-03-21 20 views
-2

確かにこの質問は尋ねられて何度も答えられましたが、メインプログラムから関数を正しく呼び出すことができませんでした。私は以下のように3つの別々のファイルを持っています。私はmaxmain.cppをコンパイルするとcppのmain関数から関数を呼び出す

//max.h 
int max(int num1, int num2); 


//maxmain.cpp 
#include <iostream> 
#include "max.h" 
using namespace std; 

// function declaration 
int max(int num1, int num2); 

int main() 
{ 
    // local variable declaration: 
    int a = 100; 
    int b = 200; 
    int ret; 

    // calling a function to get max value. 
    ret = max(a, b); 

    cout << "Max value is : " << ret << endl; 

    return 0; 
} 


//max.cpp 
#include "max.h" 
// function returning the max between two numbers 
int max(int num1, int num2) 
{ 
    // local variable declaration 
    int result; 

    if (num1 > num2) 
     result = num1; 
    else 
     result = num2; 

    return result; 
} 

、私はエラーを取得:書かれたよう maxmain.cpp:(.text+0x21): undefined reference to max(int, int) collect2: error: ld returned 1 exit status

+1

コードは問題ありません。コンパイル方法に問題があります。コンパイルに何を使っていますか(Visual Studio、gccなど)? – CoryKramer

+0

@CoryKramer私はLinux上です。 'g ++ maxmain.cpp -o maxmain' –

+0

別々にコンパイルした後にオブジェクトをコンパイルまたはリンクする際に、すべての.cppファイルの名前を与える必要があります。 –

答えて

2

あなたのコードは大丈夫です。問題はあなたがどのようにコンパイルしているかです。この場合、すべてのcppファイルを一覧表示する必要があります。

g++ maxmain.cpp max.cpp -o maxmain 
+0

ああ..私の悪い!!ご回答有難うございます。 –

関連する問題