如何在 C 中使用空的 main() 方法运行函数?
How to run a function with empty main() method in C?
这种方法在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
这可能是你需要使用的诡计水平。
相关文章:
- C++ assigment std::list:<typename>:itrator 在 main 中工作,但在方法中它不起作用
- 如何在 C 中使用空的 main() 方法运行函数?
- std::chrono 在从 main 或 from 类方法使用时给出不同的值
- main.cpp从 .h 文件调用公共虚拟方法
- 在 C++ 中解析 main 函数的大量输入的正确方法是什么
- C :使用Main中定义的对象方法的函数
- C++ - 在 main() 方法内的类实例中创建一个线程并调用 Sleep()
- C++ - 类方法更改成员变量,但不在 main 中
- main.cpp:(.text+0x8f):对[对象方法]的未定义引用
- 如何在 Main 方法之外将字符串拆分为标记
- 在类方法中包括Main()的容器
- 在 之前执行代码。NET 的 Main() 方法
- c++:在main方法中运行函数
- Main 方法与教程中的方法不同
- 为什么c中的main方法总是放在类中,而不是放在c++中
- 如何为c++可执行文件中的main()方法使用main.cpp以外的文件名
- 花括号和main方法中的返回值
- 更改Code::Blocks中的main方法
- 在main方法中调用返回String的函数
- C++:新建空项目(如何创建,添加main方法并打印"Hello, world")?