2012-04-18 137 views
0

我不知道为什么我收到此错误联系起来,我敢肯定一切都正确连接不知道为什么我得到一个链接错误

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 

我有以下的代码,这是一个简单的链表,但我不知道为什么它不会编译

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 

任何帮助将appricated

回答

2

target.h使用:

extern struct target_node * first; 

,并放置在适当的target.c文件中:

struct target_node * first = NULL; 

如果在target.c之外不需要first,则可以将其从target.h中删除(如果您想避免将其放入全局命名空间中,可以将它从static中删除)。

1

有外部连接的对象只能在整个程序中定义一次。

您在一个头文件中定义struct target_node * first,然后将该头文件包含到两个不同的实现文件中。现在你的程序中有两个定义first。而first是一个外部链接的对象。因此错误。

+0

在target.c文件的头文件或外部文件中使它外接会更好吗?什么会更有意义/共同的地方 – 2012-04-18 01:22:37

+0

@Greg:在标题中设置为'extern' - 对象的所有用户都需要获取'extern'声明,以便它们不定义它。只有对象的“所有者”才能定义/初始化它。 – 2012-04-18 01:32:29

+0

@MichaelBurr好的谢谢 – 2012-04-18 01:36:07

相关问题