【问题标题】:Multiple Definitions first defined here此处首先定义了多个定义
【发布时间】:2014-10-02 02:32:07
【问题描述】:

由于某种奇怪的原因,每次我编译我的项目时,都会收到这个奇怪的多重定义错误,即使这是我定义函数的唯一地方。我使用代码块作为我的 IDE,使用 GCC 作为编译器。代码如下:

#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;
}

【问题讨论】:

  • 显示warning消息。
  • 删除test.h,只要您在代码末尾添加},它应该可以正常工作!
  • “多个定义”听起来像是链接器错误,而不是编译器错误。您的编译和链接命令是什么样的?与您的问题无关,但您的 checkForSquare() 函数至少存在一个大问题。您不能假设squared[] 的内容会从一个调用持续到下一个调用。您可以将其声明为全局,或在main() 中声明并将其作为参数传递,或者您可以将其声明为static,但无论如何,最好先显式初始化它。跨度>
  • 另外,你不需要在函数中循环10000次,用num替换10000
  • 这不是我见过的最有效的方格检查器

标签: c function


【解决方案1】:

首先,您可以查看以下讨论: How to prevent multiple definitions in C?

其次,请至少在发布问题之前正确对齐您的代码。

第三,我认为你的 checkForSquare() 应该是这样的:

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;
}

【讨论】:

  • 请不要重新发布格式化的代码,只需编辑问题。
  • @WernerHenze 他没有足够的代表
猜你喜欢
  • 2013-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
相关资源
最近更新 更多