【发布时间】:2017-04-01 17:13:16
【问题描述】:
我在使用多个文件时遇到了一点问题。 我的任务是使用三个文件:function.h、function.cpp、prog.cpp。
在function.h中我定义了每个函数。
在function.cpp中我放了每个函数的代码。
在 prog.cpp 我必须调用函数。我没有任何定义。
我有这些错误:
"void __cdecl randInt(int *,int)" (?randInt@@YAXPAHH@Z) already defined in function.obj
"void __cdecl showInt(int *,int)" (?showInt@@YAXPAHH@Z) 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" -
在 function.h 中我定义了每个函数。 - 你声明了这些函数。 在function.cpp 中我把每个函数的代码。 - 你定义 函数。要从任何地方调用函数,您只需要声明。所以你应该只包含这些声明所在的头文件。
-
在
function.h文件中包含#include function.cpp并删除为上述cmets 中提到的#include function.cpp或尝试使用#ifndef。#ifndef检查给定的标记是否已在文件或包含文件的前面#defined;如果没有,它包含它之间的代码 -
@daemon7osh 你误解了一些东西。在
*.h中通常不包含*.cpp。