gpt4 book ai didi

c - 在 C 中将 makefile 与多个文件一起使用时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-04 06:42:44 26 4
gpt4 key购买 nike

开始为我的 C 程序设计 makefile,但在尝试包含多个文件时遇到了一些麻烦。忽略以下程序不完整的事实(在功能方面而非编译方面),我正在尝试使用 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()
{
}

ma​​in.c

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

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

getNewInt(intList);

return EXIT_SUCCESS;
}

最佳答案

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

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

#include "IntList.h"

关于c - 在 C 中将 makefile 与多个文件一起使用时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5699058/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com