c++ - 如何在 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() {}
解决方案
没有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 程序启动
推荐阅读
- javascript - 如何保存可以立即导出的 JavaScript 对象?
- android - Android Studio / com.android.support:appcompat-v7:27.1.1 红色下划线
- tensorflow - TensorBoard 不显示图像
- laravel - 如何在创建的 WordPress 中调用 API 路由
- javascript - Angular 6+ 中的透明包装器组件
- python - 调用自身内部的函数以使用 if 语句检查错误输入,if 语句永远不会中断和无限循环
- android - 如何将布局创建为从下方弹出的对话框
- service-worker - 不支持请求方法“POST”
- vba - 有没有办法在 MS Word VBA 中使用查找表?
- python - python3 subprocess.run() get 系统找不到Windows docker容器中指定的文件