读书人

多次定义?该怎么处理

发布时间: 2012-05-16 23:40:10 作者: rapoo

多次定义???
//a.h

C/C++ code
#ifndef A_H#define A_H#include <stdio.h>#include <string.h>#define LEN        (10)struct Student{    char *name;    int age;};void print_str(char *str){    printf("%s\n", str);    return ;}void print_int(int val);#endif


//a.c
C/C++ code
#include "a.h"void print_int(int val){    printf("value is : %d\n", val);    return ;}


//main.c
C/C++ code
#include <stdio.h>#include <stdlib.h>#include <string.h>#include "a.h"int main(){    char *str = "hello";    struct Student st1;    st1.name = "L";    st1.age = 18;    print_str(str);    print_str(st1.name);    print_int(st1.age);    printf("main end!\n");    return 0;}


后在gcc中运行
gcc -c main.c
gcc -c a.c
gcc -o main main.o a.o
结果显示:

a.o: In function `print_str':
a.c:(.text+0x0): multiple definition of `print_str'
main.o:main.c:(.text+0x0): first defined here
collect2: ld returned 1 exit status



为什么会多次定义????

[解决办法]
void print_str(char *str)
{
printf("%s\n", str);
return ;
}

放.c里,否则main.c和a.c都定义了同一个函数。

读书人网 >UNIXLINUX

热点推荐