简体   繁体   English

在 g++ 中编译 C 文件和 C++ 文件

[英]Compiling C files along with C++ file in g++

I'm having a custom C header file that I have created.我有一个我创建的自定义 C header 文件。 There are several files in my directory as follows.我的目录中有几个文件如下。

lib1/
     -lib1.h
     -lib1.c
lib2/
     -lib2.h
     -lib2.c
-lib_main.c
-lib_main.h
-main.c
-main.cpp
-Makefile

Now, for testing the header file with a test file called main.c, I will be giving the following command in the terminal,现在,为了使用名为 main.c 的测试文件测试 header 文件,我将在终端中给出以下命令,

gcc lib_main.c lib1/lib1.c lib2/lib2.c main.c -o ./main

Now, how could I test the same header files with main.cpp instead of main.c, how do I change it?现在,我如何使用 main.cpp 而不是 main.c 测试相同的 header 文件,我该如何更改它?

You should (and most probably must ) compile separately the c and c++ sources into a object file, and then link together.您应该(并且很可能必须)将 c 和 c++ 源代码分别编译到 object 文件中,然后链接在一起。

As an example举个例子

gcc -c -o lib1.o lib1/lib1.c
gcc -c -o lib2.o lib2/lib1.c
gcc -c -o lib_main.o lib_main.c
g++ -c -o main.o main.cpp
g++ -o main lib1.o lib2.o lib_main.o main.o

The first four commands create a series of object files, with extension.o.前四个命令创建一系列 object 文件,扩展名为.o。 The last command link together the object files into an executable.最后一个命令将 object 文件链接到一个可执行文件中。 Obviously you need to add the relevant compiler options for each source.显然,您需要为每个源添加相关的编译器选项。

Two important points to notice:需要注意的两个重要点:

  • Order of files in the linking is important.链接中的文件顺序很重要。 See discussion here and here .请参阅此处此处的讨论。

  • To mix c and c++ code with each other, for example if a c++ code calls a c function, you need to follow specific guidelines . To mix c and c++ code with each other, for example if a c++ code calls a c function, you need to follow specific guidelines .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM