我制作了一个仍在开发中的程序。我没有故意在我的程序中声明 main。因为我正在开发一个库来制作我将在我的程序中使用的图形和其他算法。在 C 中开发这样一个库的目的是解决本书 Introduction to 中给出的问题算法 Thomas H Coreman 如果有人想看,这里是代码。
#include<stdio.h>
#include<stdlib.h>
#define GREY 1
#define BLACK 0
#define WHITE 2
typedef struct node *graph;
graph cnode(int data); //cnode is to create a node for graph
void cgraph(void);
struct node {
int data, color;
struct node *LEFT, *RIGHT, *TOP, *DOWN;
};
graph root = NULL;
void cgraph(void)
{
int n, choice, dir, count;
choice = 1;
count = 1;
graph priv, temp;
printf("Printf we are making a graph the first is root node\n");
while (choice == 1) {
count++;
if (count == 1) {
printf("This is going to be root node \n");
scanf("%d", &n);
root = cnode(n);
count--;
priv = root;
} //ending if
else {
printf
("Enter direction you want to go LEFT 1 RIGHT 2 TOP 3 DOWN 4\n");
scanf("%d", &dir);
printf("Enter the data for graph node\n");
scanf("%d", &n);
temp = cnode(n);
if (dir == 1) {
priv->LEFT = temp;
}
if (dir == 2) {
priv->RIGHT = temp;
}
if (dir == 3) {
priv->TOP = temp;
}
if (dir == 4) {
priv->DOWN = temp;
}
priv = temp;
} //ending else
printf
("Enter 1 to continue adding nodes to graph any thing else would take you out\n");
scanf("%d", &choice);
} //ending while
} //ending main
graph cnode(int data)
{
graph temp = (graph) malloc(sizeof(graph));
temp->data = data;
temp->LEFT = NULL;
temp->RIGHT = NULL;
temp->TOP = NULL;
temp->DOWN = NULL;
temp->color = -1;
return temp;
}
当我编译上述程序时出现以下错误。
cc graph.c
/usr/lib/gcc/x86_64-linux-gnu/4.4.3/../../../../lib/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: ld returned 1 exit status
这个错误意味着什么,我为什么要在我的程序中声明 main?
最佳答案
默认情况下,gcc
(和大多数 C 编译器)编译并链接到一个独立的可执行文件。 main()
函数是必需的,以便启动代码知道应该从哪里开始执行代码。
要在不链接的情况下编译库代码,请使用 gcc -c graph.c
。在这种情况下,graph.c
不需要 main()
函数。
关于c - 为什么程序中必须有main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4264367/