Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

include guards not working

I've defined a util.h file with functions that i want to use throughout several different other files. This header has an include guard, however when i use it in two different files, I get a multiple definition of... error. What am i doing wrong?

I've read this but this pertains to variable declaration/definition. This answer seems more relevant but it's not clear to me how i can fix 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() {

}
like image 908
xst Avatar asked Oct 19 '12 20:10

xst


1 Answers

You are getting a linker error, not a compiler error. You have implemented the function randarr() in your util.h file, which means the compiler sees a copy of randarr() in each of example.cpp and Main.cpp. When the linker goes to link these together, it complains because you're not permitted to have more than one definition of the same function.

You have two choices:

  • declare randarr() as inline in the header file
  • move the definition for randarr() to a util.cpp file

Apply the same fix to is_prime().

like image 64
Greg Hewgill Avatar answered Oct 01 '22 01:10

Greg Hewgill