2017-04-01 20 views
-1

我在使用多個文件時遇到了一些問題。 我有一個任務使用三個文件:function.h,function.cpp,prog.cpp如何在多個文件中使用函數,C++

function.h我定義了每個函數。

function.cpp我把每個函數的代碼。

prog.cpp我必須調用函數。在那裏我沒有任何定義。

我有這些錯誤:

"void __cdecl randInt(int *,int)" ([email protected]@[email protected]) already defined in function.obj 

"void __cdecl showInt(int *,int)" ([email protected]@[email protected]) already defined in function.obj 

One or more multiply defined symbols found 

function.cpp:

#include <iostream> 
using namespace std; 

void randInt(int *arr, int size) { 
    for (int *i = arr; i < arr + size; i++) { 
     *i = rand() % 10; 
    } 

} 
void showInt(int *arr, int size) { 
    cout << "Int Massive" << endl; 
    for (int *i = arr; i < arr + size; i++) { 
     cout << *i << ", "; 
    } 
    cout << endl; 
} 

function.h:

#pragma once 
void randInt(int *, int); 
void showInt(int *, int); 

prog.cpp:

#include <iostream> 
#include <ctime>; 
using namespace std; 
#include "function.h" 
#include "function.cpp" 


int main() 
{ 
    srand(time(0)); 
    int n = 10; 
    int *arrInt = new int[10]; 
    randInt(&arrInt[0], n); 
    showInt(&arrInt[0], n); 
    return 0; 
} 
+1

您的'prog.cpp'明確包含'function.cpp'。那是你的問題。 –

+2

刪除'#include'function.cpp「' –

+2

_In function.h我定義了每個函數._ - 你聲明瞭函數。 _在function.cpp中,我把每個函數的代碼._ - 你*定義*的功能。要從任何地方調用函數,只需要*聲明*。所以你應該只包含這些聲明所在的頭文件。 – zett42

回答

6

這是不正確的,不需要包括的.cpp文件,因此刪除#include "function.cpp",你應該罰款。

+0

是的,這是工作。 –

+0

所以接受答案 – apmccartney

+0

1分鐘接受 –

1

你應該這樣

function.h

#pragma once 
    void randInt(int *, int); 
    void showInt(int *, int); 

fuction.cpp

#include <iostream> 
    #include "function.h" 
    using namespace std; 

    void randInt(int *arr, int size) { 
     for (int *i = arr; i < arr + size; i++) { 
      *i = rand() % 10; 
     } 

    } 
    void showInt(int *arr, int size) { 
     cout << "Int Massive" << endl; 
     for (int *i = arr; i < arr + size; i++) { 
      cout << *i << ", "; 
     } 
     cout << endl; 
    } 

prg.cpp

編輯文件
#include <iostream> 
    #include <ctime>; 
    #include "function.h" 
    using namespace std; 

    int main() 
    { 
     srand(time(0)); 
     int n = 10; 
     int *arrInt = new int[10]; 
     randInt(&arrInt[0], n); 
     showInt(&arrInt[0], n); 
     return 0; 
    } 

然後你可以通過鏈接prg.cpp和你的function.cpp文件來編譯你的程序。如果你正在使用g ++編譯器,你可以按照下面的方式來完成。

g++ prg.cpp fuction.cpp 
相關問題