【发布时间】:2012-10-19 20:08:12
【问题描述】:
我已经定义了一个 util.h 文件,其中包含我想在其他几个不同文件中使用的函数。这个头文件有一个包含保护,但是当我在两个不同的文件中使用它时,我得到一个multiple definition of... 错误。我做错了什么?
我已阅读 this 但这与变量声明/定义有关。 This 答案似乎更相关,但我不清楚如何解决这个问题。
// util.h
// include lots of standard headers
#include ...
#ifndef UTIL_H
#define UTIL_H
using namespace std;
// multiple definition of `randarr(int, int, int)`
int* randarr(int size, int min, int max) {
int *ret = new int[size];
for (int i=0; i<size; i++)
ret[i] = (int) (((double) rand() / RAND_MAX) * max) + min;
return ret;
}
// no error
template<typename T> void printarr(T* v, int begin, int end) {
for (int i=begin; i<end; i++)
cout << v[i] << " ";
cout << endl;
}
// multiple definition of `is_prime(int)`
bool is_prime(int n) {
if (n == 2 || n == 3 || n == 5) return true;
if (n <= 1 || (n&1) == 0) return false;
for (int i = 3; i*i <= n; i += 2)
if (n % i == 0) return false;
return true;
}
#endif
// example.cpp
#include ...// lots of standard includes
#include "util.h"
void f() {
randarr(...);
printarr(...);
is_prime(...);
...
}
// Main.cpp
#include "util.h"
int main() {
}
【问题讨论】:
-
你从 util.h 中包含的所有文件是否都包含保护。 2:也许有人在某个地方取消了 UTIL_H 宏的定义。
-
你应该让randarr()成为一个内联函数!
-
不值得回答,但没有人评论过头文件中的
using namespace std;。正如我们在德克萨斯州所说,“拿一根绳子”。 -
我将原型和实现分开,但在这种情况下内联所有函数效果最好,因为函数都很短
标签: c++ include compiler-errors