我对C和多个源文件的代码是新手.
我有一个头文件进度h:进度h
和源文件进度c:进度c
,其中name
和age
是使用extern
关键字声明的,其中set_data
和print_data
在手C
中访问它们.但它显示了一些链接错误.
我到底做错了什么?
进度h:进度h
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <error.h>
#define ERROR(s) perror(s)
#define BUFF 1024
extern char* name;
extern int age;
void print_data(char* name, int age);`
进度c:进度c
#include "进度h:进度h"
void set_data(char* a_name, int a_age)
{
name = a_name;
age = a_age;
}
void print_data(char *name, int age)
{
printf("Name: %s\nAge: %d\n", name, age);
}
手C
#include "进度h:进度h"
#include <stdlib.h>
int main(int argc, char **argv)
{
set_data(argv[1], argv[2]);
print_data(name, age);
return EXIT_SUCCESS;
}
GCC:
gcc -o main 手C 进度c:进度c
错误:
`手C: In function ‘main’:
手C:6:5: warning: implicit declaration of function ‘set_data’ [-Wimplicit-function-declaration]
6 | set_data(argv[1], argv[2]);
| ^~~~~~~~
/usr/bin/ld: /tmp/ccWK8fek.o: warning: relocation against `name' in read-only section `.text'
/usr/bin/ld: /tmp/ccR60C2Q.o: in function `main':
手C:(.text+0x3b): undefined reference to `age'
/usr/bin/ld: 手C:(.text+0x42): undefined reference to `name'
/usr/bin/ld: /tmp/ccWK8fek.o: in function `set_data':
进度c:进度c:(.text+0x16): undefined reference to `name'
/usr/bin/ld: 进度c:进度c:(.text+0x1f): undefined reference to `age'
/usr/bin/ld: warning: creating DT_TEXTREL in a PIE
collect2: error: ld returned 1 exit status
我已经在网上搜索过了,我试着用extern
个关键词,但,它不起作用.