3
votes

This is a problem I have in a piece of code I'm working on. Basically, I'm trying to compile my code and I keep getting the error: "Multiple Definition of "Top", pointed at my stack.c file (the one that contains the functions) with "first defined here" pointed at my main.c file. From reading the other questions with similar names, it seems to be something related to the includes. Here's the header file:

#ifndef STACK_H
#define STACK_H
#define MAXSIZE 10

struct stekas{
int content;
struct stekas *link;
}*top = NULL;

void push(void);
void pop(void);
void display(void);
void help(void);

#endif // STACK_H_INCLUDED

The stack.c and main.c files both have the exact same #includes and #defines:

#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
#define MAXSIZE 10

Note that "top" is not once referred to in main.c. Again, if needed, I can post the entire code of the stack.c file if it's needed.

1

1 Answers

0
votes

Look at these four lines in your header:

struct stekas {
    int content;
    struct stekas *link;
}*top = NULL;

These lines do three things:

  1. Declare a structure called struct stekas,
  2. Declare a variable of type struct stekas called top, and
  3. Provide a definition for the variable top.

Items 1 and 2 are supposed to be in the header, while item 3 should be in a C file, not in the header.

The problem with putting definitions in a header is that every time you include a header from a C file, that C file makes a new definition for whatever is defined in the header. If you include your header from three C files, linker will see three conflicting definitions of top, even if you never refer to that variable anywhere in the code of these C files.

Change your header as follows:

struct stekas {
    int content;
    struct stekas *link;
};
extern struct stekas *top;

Add this line to any of your C files:

struct stekas *top = NULL;

This will fix the linking problem.