Greg Brown
Greg Brown

Reputation: 1299

Don't know why I am getting a linking error

I don't know why I am getting this linking error, I am pretty sure everything is linked correctly

gcc -Wall -Wextra -o test driver.c target.c 
driver.c:8: warning: unused parameter ‘argc’
ld: duplicate symbol _first in /var/folders/yx/31ddgzsj4k97jzvwhfx7tkz00000gn/T//ccw2n48G.o and /var/folders/yx/31ddgzsj4k97jzvwhfx7tkz00000gn/T//ccKZdUlG.o for architecture x86_64
collect2: ld returned 1 exit status

I have the following code, which is a simple linked list, but I don't know why it wont compile

driver.c

 #include "target.h"
 #include <stdio.h>
 #include <stdlib.h>

char * prog;
int main(int argc, char * argv[]){
  prog = argv[0];
  print_target_list(1);
  .....

target.c

#include "target.h"
/* This function returns true if there is a target with name in the target linked list */
bool is_target(char * name){
    struct target_node * ptr = first;
   while(ptr != NULL){
    if(strcmp(ptr->name,name) == 0){
      return true;
    }
    ptr = ptr->next;
  }
  return false;
}
......

target.h

#ifndef TARGET_H
#define TARGET_H

//#include "source.h"
#include <stdbool.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

/*-----------------------------------------*/

extern char * prog;

/*-----------------------------------------*/

struct source_node{
  char * name;
};

struct target_node{
  char * name;
  struct target_node * next;
  struct source_node * src_node;
};

struct target_node * first = NULL;

/*-----------------------------------------------------*/


/* return 1 if name is in the target linked list 0 otherwise */
bool is_target(char * name);
/* returns a new target_node */ 
struct target_node * new_target_node(char * name);
/* insert a new target_node into the list */
void insert_target_node(char * name);
/* remove a target_node from the list */
void remove_target_node(char * name);
/* print the current linked list */
void print_target_list(int opts);


#endif

Any help would be appricated

Upvotes: 0

Views: 230

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320361

Objects with external linkage have to be defined only once in the entire program.

You defined struct target_node * first in a header file and then included that header file it into two different implementation files. Now you have two definitions of first in your program. And first is an object with external linkage. Hence the error.

Upvotes: 1

Michael Burr
Michael Burr

Reputation: 340168

In target.h use:

extern struct target_node * first;

And place the following in the appropriate target.c file:

struct target_node * first = NULL;

If first isn't needed outside of target.c, it can be removed from target.h altogether (and maybe made static in target.c if you want to avoid putting it in the global namespace needlessly).

Upvotes: 2

Related Questions