为什么在程序中主要是必要的

rea*_*ays 3 c

我制作了一个仍在开发中的程序.我没有故意在我的程序中声明main.因为我正在开发一个用于制作图形和其他算法的库,我将在我的程序中使用.在C中开发这样一个库的目的是解决书中给出的问题.算法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;
}
Run Code Online (Sandbox Code Playgroud)

当我编译上面的程序时,我得到了以下错误.

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
Run Code Online (Sandbox Code Playgroud)

这个错误意味着什么,我为什么要在我的程序中声明main?

caf*_*caf 14

默认情况下,gcc(和大多数C编译器)编译并链接到独立的可执行文件.该main()函数是必需的,以便启动代码知道应该从哪里开始执行代码.

要在不链接的情况下编译库代码,请使用gcc -c graph.c.在这种情况下,graph.c不需要main()功能.


Jay*_*Jay 5

main 如果要将代码构建到应用程序中,则必须存在,因为主要功能用作应用程序的入口点.

但是,如果您的代码是作为lib构建的,则不需要main.

编辑:检查此信息以获取有关静态库和共享库的信息.


pax*_*blo 5

为什么?因为标准(大部分)是这么说的。

该main函数是托管 C 环境所必需的(允许独立环境以任何它们喜欢的方式启动)。

如果您正在开发一个库,则该库本身不需要main,但如果没有它,您将无法将其转换为可执行文件(除非使用不可移植的技巧)。而且,无论如何,您至少应该有一个用于测试套件。

换句话说,您的库应该有一个由main函数控制的大型测试套件(很可能在一个或多个单独的源文件中),以便您可以测试任何新工作和回归测试,以确保它没有填满旧工作。