-3

For some strange reason every time I compile my project I get this strange error of multiple definitions even though this is the only place I define my function. I use code blocks as my IDE and GCC as the compiler. Here is the code:

#include <stdio.h>
#include <test.h>

int checkForSquare(int num){
    int squared[10001];
    squared[num] = num * num;
    for(int i = 0; i <= 10000; i++){
        if(squared[i] == num){
            return 1;
            break;
        }
    }
return 0;
}

int main(){
    for(int x = 0;x <=10000;x++){
        if(checkForSquare(x))
            printf( "%d" , x );
        else
            printf("Not Square");
    }

return 0;
}
Yurii
  • 4,811
  • 7
  • 32
  • 41
  • 3
    Show the `warning` message. – rakib_ Oct 02 '14 at 02:33
  • Remove `test.h` and it should work fine provided that you put a `}` in the end of the code! – Spikatrix Oct 02 '14 at 02:57
  • 1
    "Multiple definitions" sounds like a linker error, not a compiler error. What do your compilation and linking commands look like? Unrelated to your problem, but there's at least one big problem with your `checkForSquare()` function. You can't assume that the contents of `squared[]` will persist from one call to the next. You could declare it as a global, or declare it in `main()` and pass it as an argument, or you could declare it as `static`, but in any case, it would be good practice to explicitly initialize it first. – Jim Lewis Oct 02 '14 at 03:04
  • Also,you don't need to loop 10000 times in the function,replace 10000 by num – Spikatrix Oct 02 '14 at 03:14
  • This is not the most efficient square-checker I've ever seen – M.M Oct 02 '14 at 06:27

1 Answers1

-1

First, you can check the discussion below: How to prevent multiple definitions in C?

Second, please properly align your code at least before you post your question.

Third, I think your checkForSquare() should look like this:

int checkForSquare(int num){
    static long squared[10001];
    squared[num] = num * num;
    for(int i = 1; i < num; ++i){
        if(squared[i] == num){
            return 1;
        }
    }
    return 0;
}
Community
  • 1
  • 1
JHT
  • 72
  • 5