【问题标题】:how to prevent the error multiple definition of main function in c?如何防止c中main函数的错误多重定义?
【发布时间】:2020-04-29 22:19:31
【问题描述】:

我收到以下错误:

在 main 函数中: electionTestsExample.c:(.text+0xf7): 'main' 的多重定义 /tmp/cc5EeMIa.o:electionTestsExample.c:(.text+0xf7): 首先在这里定义

即使我只有一个主要功能 这是我的electionTestsExample.c:

#include <stdlib.h>
#include "elections.h"
#include "test_utilities.h"

/*The number of tests*/
#define NUMBER_TESTS 1

static bool deleteOnlyFirstArea (int area_id) {
    return area_id == 1;
}

static bool testElectionRemoveAreas() {
    Election election = electionCreate();
    ASSERT_TEST(electionAddArea(election, 1, "first area") == ELECTION_SUCCESS);
    ASSERT_TEST(electionAddArea(election, 2, "second area") == ELECTION_SUCCESS);

    ASSERT_TEST(electionRemoveAreas(election, deleteOnlyFirstArea) == ELECTION_SUCCESS);
    electionDestroy(election);
    return true;
}

/*The functions for the tests should be added here*/
static bool (*tests[]) (void) = {
                      testElectionRemoveAreas
};

/*The names of the test functions should be added here*/
static const char* testNames[] = {
                           "testElectionRemoveAreas"
};

 int main(int argc, char *argv[]) {
    if (argc == 1) {
        for (int test_idx = 0; test_idx < NUMBER_TESTS; test_idx++) {
              RUN_TEST(tests[test_idx], testNames[test_idx]);
        }
        return 0;
    }
    if (argc != 2) {
      fprintf(stdout, "Usage: election <test index>\n");
      return 0;
  }

  int test_idx = strtol(argv[1], NULL, 10);
  if (test_idx < 1 || test_idx > NUMBER_TESTS) {
      fprintf(stderr, "Invalid test index %d\n", test_idx);
      return 0;
  }

  RUN_TEST(tests[test_idx - 1], testNames[test_idx - 1]);
  return 0;
}

这是我的生成文件:


CC=gcc
OBJS = electionTests.o election.o electionelem.o vote.o
EXEC = election
DEBUG_FLAG = -g
COMP_FLAG = -std=c99 -Wall -Werror
$(EXEC) : $(OBJS)
$(CC) $(DEBUG_FLAG) $(OBJS) -o $@
electionTests.o : electionTestsExample.c elections.h test_utilities.h
$(CC) -c $(DEBUG_FLAG) $(COMP_FLAG) $*.c
election.o : elections.c elections.h election_element.h votes.h map.h
$(CC) -c $(DEBUG_FLAG) $(COMP_FLAG) $*.c
electionelem.o : election_element.c election_element.h votes.h
$(CC) -c $(DEBUG_FLAG) $(COMP_FLAG) $*.c
vote.o : votes.c votes.h

【问题讨论】:

  • 也许在其中一个包含中对main() 有另一种定义?
  • 没有一个没有主要功能
  • 显示你的 Make-file 或编译指令。
  • 我不是想举一个最小的例子

标签: c


【解决方案1】:

您正在查看代码,但答案在于构建。

错误来自链接器。它说main 被定义了两次,在同一个文件中,在同一个地方。这表明该文件正在链接到自身。

对于除main 之外的任何函数(可能不是函数),链接器将忽略后续定义;这就是为什么您可以覆盖 strcpy(3) 或 ma​​lloc(3) 等标准库函数的原因。但是main只能有一个,两个表示错误。

我猜你的命令行上有electionTestsExample.celectionTestsExample.o

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 2017-05-20
    • 2014-10-13
    • 1970-01-01
    • 2015-04-10
    • 2021-12-04
    相关资源
    最近更新 更多