Vik*_*oel 4 c warnings function implicit-declaration
我经历了以下线程:
可能我的问题是相关的。但是,虽然他们提供了应该在使用函数之前声明函数原型的解决方案,但我想探索当函数名称不匹配时会发生什么。在我的测试中,它仍然可以正常工作。
主 C 文件
#include "node.h"
int main(){
nd *head=NULL;
nd *tail=NULL;
create_node(&head, &tail, 10);
create_node(&head, &tail, 20);
create_node(&head, &tail, 15);
create_node(&head, &tail, 35);
create_node(&head, &tail, 5);
create_node(&head, &tail, 25);
print_list(head, tail);
create_node(&head, &tail, 55);
create_node(&head, &tail, 52);
create_node(&head, &tail, 125);
printf("%d\n",tail->data);
printf("%d\n",head->data);
print_list(head, tail);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
node.h 文件
#ifndef NODE_H
#define NODE_H
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node *next;
struct node *prev;
}nd;
void insert_node(nd **head, nd **tail, int data);
void print_list(nd *head, nd *tail);
#endif
Run Code Online (Sandbox Code Playgroud)
node.c 文件
#include "node.h"
void create_node(nd **head, nd **tail, int d){
nd *temp=(nd *) malloc(sizeof(nd));
temp->data=d;
temp->next=NULL;
temp->prev=NULL;
/* Start of the Queue. */
if(*head==NULL && *tail==NULL){
*head=temp;
*tail=temp;
}
/* Linking with tail of the Queue. */
else if((*tail)->next==NULL){
(*tail)->next=temp;
temp->prev=*tail;
*head=temp;
}
/* Adding remaining elements of the Queue. */
else{
(*head)->next=temp;
temp->prev=*head;
*head=temp;
}
}
void print_list(nd *head, nd *tail){
if(NULL==head){
printf("Queue is empty\n");
}
else{
printf("Printing the list\n");
nd *temp;
for(temp=tail;temp!=NULL;temp=temp->next){
printf("%d ",temp->data);
}
printf("\n");
}
}
Run Code Online (Sandbox Code Playgroud)
输出
Printing the list
10 20 15 35 5 25
10
125
Printing the list
10 20 15 35 5 25 55 52 125
Run Code Online (Sandbox Code Playgroud)
在node.his 中声明的函数名称insert_node在 node.c 中是create_node。有人可以分享一些关于它为什么运行的见解吗?但它会发出警告:
警告:函数的隐式声明
在您的示例中,您有一个隐式声明create_node和 声明未实现的 function insert_node。
create_node因您链接到的先前帖子中将介绍的原因而要求工作。
insert_node未实现的事实与您的程序无关,因为没有任何尝试调用它。如果您将一行更改为 call insert_node,它将在没有警告的情况下编译,但随后无法链接insert_node.
我相信您知道这一点,但这里的正确方法是标准化create_nodeor 之一insert_node并在整个程序中使用它。
首先,您已经声明了一个名为 的函数insert_node,但这并不重要。可以声明函数,但不定义它们(即不提供它们的代码),只要您不使用该函数。这种情况在现实生活中经常发生:headers 定义了很多函数,然后在链接时只需要提供实际使用的函数。
警告令人担忧create_node。由于编译主 C 文件时没有函数声明,因此编译器对其参数类型做了一些假设。它提升所有参数:小于int(例如char和short)的整数类型被提升为int;floats 被提升为double; 指针类型不会被转换。使用您的代码,这恰好可以工作,因为
如果您将data参数的类型更改为long,那么编译器将生成代码来调用假定int类型的函数,但该函数需要一个long参数。在一个平台,int并long有不同的大小,你可能会得到垃圾数据,系统崩溃,或其他不当行为。
如果您将data参数的类型更改为char,那么编译器将生成代码来调用假定int类型的函数,但该函数需要一个char参数。同样,您可能会发现代码使用了错误的数据、崩溃等。
C 通常会给你足够的绳子让你上吊。如果你以错误的方式剪断一根绳子,它可能恰好起作用。或者它可能不会。