C语言 如何在没有 main 函数的情况下编译 C 源代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5764298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:27:51  来源:igfitidea点击:

How to compile C source code without a main function?

c

提问by system

How can I compile my C source files without needing to put a mainfunction within them?

如何编译我的 C 源文件而不需要main在其中放置函数?

I get an error for the .cfiles that have no main function and don't want to have to add the main function just for compilation.

对于.c没有 main 函数并且不想只为了编译而添加 main 函数的文件,我收到错误消息。

回答by Kos

On GCC, the -cswitch is what you want.

在 GCC 上,-c开关就是你想要的。

-cmeans "compile, don't link", and you get a name.ooutput file.

-c意思是“编译,不链接”,你会得到一个name.o输出文件。

回答by Vignesh

Suppose you have hello.c:

假设你有 hello.c:

#include<stdio.h>
#include<stdlib.h>
_start()
{
   exit(my_main());
}
int my_main()
{
   printf("Hello");
   return 0;
}

Compile as:

编译为:

gcc  -nostartfiles  hello.c 

and you can get an executable out of it.

你可以从中得到一个可执行文件。

回答by Pascal Cuoq

Use the -coption of your compiler (works for GCC, option probably identical for other c compilers).

使用-c编译器的选项(适用于 GCC,其他 c 编译器的选项可能相同)。

From GCC's man page:

从 GCC 的手册页:

When you invoke GCC, it normally does preprocessing, compilation, assembly and linking. The "overall options" allow you to stop this process at an intermediate stage. For example, the -c option says not to run the linker. Then the output consists of object files output by the assembler.

当您调用 GCC 时,它通常会进行预处理、编译、汇编和链接。“整体选项”允许您在中间阶段停止此过程。例如,-c 选项表示不运行链接器。然后输出由汇编器输出的目标文件组成。

The linking phase is the step that looks for main()and complains if it doesn't find it.

链接阶段是寻找main()并在找不到时抱怨的步骤。

回答by R.. GitHub STOP HELPING ICE

You can compileindividual files without main, but you cannot linkthem and of course cannot runthem since they are not complete programs. Note that valgrind is not a static analysis tool but a runtime tool, and therefore it is useless on individual translation units not linked into a runnable program.

您可以在没有 的情况下编译单个文件main,但不能链接它们,当然也不能运行它们,因为它们不是完整的程序。请注意,valgrind 不是静态分析工具,而是运行时工具,因此它对未链接到可运行程序的单个翻译单元无用。

If you want to test individual files, a common practice is to include something like the following in each file:

如果要测试单个文件,通常的做法是在每个文件中包含如下内容:

#ifdef UNIT_TEST
int main(int argc, char **argv)
{
    /* unit test code goes here */
}
#endif

And compile the file with -DUNIT_TEST.

并用-DUNIT_TEST.