麻烦在C中使用带有多个文件的makefile

时间:2011-04-18 05:56:32

标签: c compiler-construction makefile

开始了解我的C程序的makefile文件,但在尝试包含多个文件时遇到了一些麻烦。忽略下面的程序不完整(在功能方面而不是编译方面)的事实,我正在尝试使用make文件编译和运行该程序。

这是我的make文件:

main: main.o IntList.o
    gcc -o main main.o IntList.o

main.o: main.c
    gcc -c -ansi -pedantic -Wall main.c

IntList.o: IntList.c IntList.h
    gcc -c -ansi -pedantic -Wall Intlist.c

这是我收到的错误:

gcc -c -ansi -pedantic -Wall Intlist.c
gcc -o main main.o IntList.o
ld: duplicate symbol _getNewInt in IntList.o and main.o
collect2: ld returned 1 exit status
make: *** [main] Error 1

该计划的代码如下。我不确定是make文件还是程序文件中包含的导致问题(或两者都有!)

任何帮助都会很棒。欢呼声。

编辑:在模块化方面引导我走向正确方向的任何提示都会非常受欢迎,因为我不确定我是否这样做是最好的方法。

IntList.h

#include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

/* Constants */
#define MAX_INTS 10

/* Signed ints can have a maximum of 10 digits. We make the length 11 to 
 * allow for the sign in negative numbers */
#define MAX_INPUT_LENGTH 11
#define EXTRA_SPACES 2

/* Typedefs / Structs */
typedef struct {
   int list[MAX_INTS];
   int noInts;
} IntList;

/* Proto Types */
int insertIntToList(int *list);
void shiftList(int offset);
void displayList();

IntList.c

#include "IntList.h"

int getNewInt(int *list)
{
   int valid = 0, inputInt;
   char inputString[MAX_INPUT_LENGTH + EXTRA_SPACES];

   while(!valid)
   {
      printf("Input an int: ");

      valid = 1;

      if((fgets(inputString, MAX_INPUT_LENGTH + EXTRA_SPACES, stdin)) != NULL)
      {
         sscanf(inputString, "%d", &inputInt);
         /* Check first that the input string is not too long */
         if(inputString[strlen(inputString) - 1] != '\n')
         {
            printf("\nError: Too many characters entered \n");
            valid = 0;
         }

         printf("\nThe Int: %d", inputInt);
         printf("\n");
      }
   }
}

void shiftList(int offset)
{
}

void displayList()
{
}

的main.c

#include <stdio.h>
#include <stdlib.h>
#include "IntList.c"

int main(void)
{
   int intList[10];

   getNewInt(intList);

   return EXIT_SUCCESS;
}

6 个答案:

答案 0 :(得分:3)

不要在main中包含.c文件,包含.h文件。否则,IntList.c中的代码会被编译到IntList.omain.o中,因此您将获得重复的符号。

在main.c而不是IntList.c中使用它:

#include "IntList.h"

答案 1 :(得分:1)

#include "IntList.c"

应该是:

#include "IntList.h"

另外(虽然与你的问题无关)我建议不要在源文件的名称中使用混合大小写,因为它可能导致可移植性问题并且很难诊断“没有这样的文件”错误 - 使用全部小写,就像标准库头一样。

答案 2 :(得分:0)

#include "IntList.c"进入main.c

答案 3 :(得分:0)

你应该

#include "IntList.c"
在你的主程序中,它应该是:

#include "IntList.h"

通过包含C文件,您可以在getNewIntmain目标文件中创建IntList,这就是为什么当您尝试链接时出现重复定义错误的原因他们在一起。

答案 4 :(得分:0)

main.c应该包含“IntList.h”,而不是“IntList.c”。

如果包含IntList.c,IntList.c中的函数将在IntList.o和main.o中实现,这将产生您看到的“重复符号”错误。

答案 5 :(得分:0)

正如其他人所提到的,你包括.h文件,而不是.c文件 此外,当您编译时,您只编译.c文件,因此您应该删除Makefile中对.h文件的任何引用