Расщепление файла AC и использование Makefile - PullRequest
0 голосов
/ 04 октября 2018

Моя цель - разбить мою программу на несколько файлов и использовать Makefile для ее запуска.Тем не менее, я продолжаю получать эту ошибку: я использовал для инициализации "int top" и в моем главном файле, но я подумал, что это может быть проблемой, однако все еще нет результатов, и я не могу найти что-нибудь в Интернете, что помогло бы мне сэта ошибка, если кто-то знает проблемы или полезный ресурс, который они могут порекомендовать мне, это было бы здорово:)

gcc -o hw5 hw5.o pushnpop.o
pushnpop.o:(.bss+0x0): multiple definition of `top'
hw5.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status
Makefile:3: recipe for target 'hw5' failed
make: *** [hw5] Error 1

******** Вот мои коды *********** ******* hw5.c *********

#include <stdio.h>
#include <curses.h>
#include <stdlib.h>
#include "pushnpop.h"
#define MAX 100


int emptyCheck(char *stack)
{
  if(stack[0] == '\0')
    return 1;
  else
    return 0;
}

int main()
{
  /*int top = 0;*/
  char c;
  char line[10000];
  FILE *file;
  char stack[MAX];
  char fileName;
  printf("Please enter a file name with a .c extension\n");
  scanf("%s", &fileName);
  /*printf("testing the name:%s\n", &fileName);*/
  file = fopen(&fileName, "r");

  /*error checking*/
  if (file == NULL)
  {
    printf("Cannot access file\n");
    exit(0);
  }

  for(int i = 0; i < MAX; i++ )
  {
    stack[i] = '\0';
  }


/*getting the data from the file*/
int lineCounter = 1;
while(fgets(line, 10000, file) != NULL)
  {
    int j = 0;
    while(line[j] != '\n')
    {
      if(line[j] == '{')
      {
        push(stack);
      }
      else if(line[j] == '}')
      {
        if(emptyCheck(stack) == 1)
        {
        printf("too many } on line %d\n", lineCounter);
        break;
        }
        else
         pop(stack);
      }

    j++;

    }

    if(emptyCheck(stack)==0)
    {
      printf("too many { on line %d\n", lineCounter);
    }

    if(fgets(line, 10000, file) == NULL)
    {
      printf("END of FILE\n");
      exit(0);
    }

    for(int i = 0; i<MAX; i++)
      stack[i] = '\0';

    lineCounter++;
    top = 0;

  }

  fclose(file);
  return 0;
}

**** мой второй файл ***** *****pushnpop.c ******

#include "pushnpop.h"


char pop(char *stack)
{
  char *temp;

    temp = stack;
    top--;
    temp[top] = '\0';

  return *temp;
}

char push(char *stack)
{
  char *temp;

  temp = stack;
  temp[top] = '{';
  top++;

  return *temp;
}

****** мой третий файл ****** **** pushnpop.h *******

#ifndef pnp
#define pnp

int top = 0;
char pop(char *stack);
char push(char *stack);

#endif

******** MAKEFILE ********

all: hw5
hw5: hw5.o pushnpop.o
    gcc -o hw5 hw5.o pushnpop.o

pushnpop.o: pushnpop.c
    gcc -o pushnpop.o -c pushnpop.c -W -Wall -pedantic

hw5.o: hw5.c pushnpop.h
    gcc -o hw5.o -c hw5.c -W -Wall -pedantic

clean:
    rm -rf *.o

mrproper: clean
    rm -rf pushnpop

Ответы [ 2 ]

0 голосов
/ 04 октября 2018

Проблема в заголовочном файле pushnpop.h

int top = 0;

Вы должны пометить это как extern.Как правило, переменные не должны быть определены в заголовочных файлах.Если требуется в двух или более файлах, они должны быть помечены как extern в заголовке.

extern int top;

Кроме того, в одном из файлов .c (возможно, pushnpop.c) необходимо определить переменную в глобальном пространстве.

int top = 0; // outside the functions
0 голосов
/ 04 октября 2018

Шаг 1, переместите int top в pushnpop и не открывайте top из main.Например,

// pushnpop.c
#include "pushnpop.h"

int top = 0;

char pop(char *stack)
{

Затем измените pushnpop.h, чтобы объявить функции extern.Например,

// pushnpop.h
#ifndef pnp
#define pnp

extern char pop(char *stack);
extern char push(char *stack);

#endif

И не забудьте закомментировать

// top = 0;

в main.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...