首页 > 解决方案 > 如何在 C 中使用空的 main() 方法运行函数?

问题描述

这种方法适用于C++,但不适用于C

它给了我这个错误initializer element is not constant

#include <stdio.h>

int n = printf("Hello World");

int main() {}

如何hello world使用空main函数进行打印?

我只需要将这段C++代码转换成C

#include <iostream>
using namespace std;

int n = printf("Hello World");

int main() {}

或这个

#include <iostream>
using namespace std;

int fun()
{
    cout << "Hello World";
    return 1;
}

int x = fun();

int main() {}

或者这个 C++ 代码

#include <iostream>
using namespace std;

int fun()
{
    cout << "Hello World";
    return 1;
}

int x = fun();

int main() {}

标签: c++cmain

解决方案


没有main()是完全可能的,但涉及重新定义_start()功能。

/*main.c*/

#include <stdio.h> 
#include <stdlib.h>

void _start() 
{  
    printf("No main function!\n");
    exit(0); 
} 

编译:

对于 Windows(10,gcc 8.1.0)和 Ubuntu(18.04,gcc 9.2.0)

gcc main.c -nostartfiles

对于 MacOS(10.14.6、Xcode 11.3)

clang -Wl,-e,-Wl,__start main.c

有关 Linux 程序启动的更多信息Linux x86 程序启动


推荐阅读