如何在 C 中使用空的 main() 方法运行函数?

How to run a function with empty main() method in C?

本文关键字:main 方法 运行 函数      更新时间:2023-10-16

这种方法在C++中有效,但在C中不起作用

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

#include <stdio.h>
int n = printf("Hello World");
int main() {}

如何使用空main功能打印hello world

我只需要将此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() {}

没有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 程序启动

如何在 C 中用空的主方法运行函数?

简答题

任何适合生产代码的方式都是不可能的。

长答案

这是可能的,但涉及很多技巧,比如重新定义程序应该从哪里开始执行。它不能以标准方式完成。C 根本不允许在函数外部进行声明和初始化以外的其他操作。

一个相关的事情是,可以将 main 声明为函数以外的其他东西。这是一篇关于编写一个程序的文章,该程序打印"Hello World!",同时将 main 声明为数组而不是函数。http://jroweboy.github.io/c/asm/2015/01/26/when-is-main-not-a-function.html

这可能是你需要使用的诡计水平。