我在使用多個文件時遇到了一些問題。 我有一個任務使用三個文件: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;
}
您的'prog.cpp'明確包含'function.cpp'。那是你的問題。 –
刪除'#include'function.cpp「' –
_In function.h我定義了每個函數._ - 你聲明瞭函數。 _在function.cpp中,我把每個函數的代碼._ - 你*定義*的功能。要從任何地方調用函數,只需要*聲明*。所以你應該只包含這些聲明所在的頭文件。 – zett42