我对C和多个源文件的代码是新手. 我有一个头文件进度h:进度h和源文件进度c:进度c,其中nameage是使用extern关键字声明的,其中set_dataprint_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个关键词,但,它不起作用.

推荐答案

变量的这些声明

extern char* name;
extern int age;

不是他们的定义.因此,编译器会发出消息,指出对变量的引用未定义.你需要给它们下定义,比如用prog.c

char* name;
int age;

函数set_data的声明在具有main的翻译单元中缺失.因此,编译器发出消息,表明该函数是隐式声明的.如果没有看到它的声明,编译器就无法判断该函数是否正确使用.以与print_data的函数声明相同的方式将函数声明放置在头prog.h中.

C++相关问答推荐

由于未签名int导致的运行时错误"

数组元素的编号索引

理解C中的指针定义

如果实际的syscall是CLONE(),那么为什么strace接受fork()呢?

__VA_OPT__(,)是否可以检测后面没有任何内容的尾随逗号?

使用GOTO从多个嵌套循环C继续

Clang:如何强制运行时错误的崩溃/异常由于-fsanitize=undefined

使用双指针动态分配和初始化2D数组

进程在写入管道时挂起

为什么此共享库没有预期的依赖项?

使用TCL C API导航到列表中的元素

在libwget中启用Cookie会导致分段故障

Tic-tac-toe:从文件加载存储

C将数组传递给函数以修改数组

我在C程序的Flex/Bison中遇到语法错误

发送和接收的消息中的Unix域套接字不匹配

被调用方函数内部的C-Struct变量,它是指针还是无关紧要

将char*铸造为空**

如何修复数组数据与列标题未对齐的问题?

可以从指针数组中的值初始化指针吗?