如何通过包含相应的 .h 文件从 .cpp 中获取 function/class 定义?

How do I get a function/class definition from a .cpp by including its corresponding .h file?

例如 A.h:

class A{
   void method();
};

并在 A.cpp 中:

#include "A.h"

void A::method(){/*do stuff*/};

并在 main.cpp

#include "A.h"

int main(){
   A a;

   a.method();
}

如何通过在 main.cpp 文件中仅包含 A.h 来访问 A.cpp 中方法的定义?是否有涉及 makefile 或 IDE 的技巧?

Is there a trick involving makefiles or IDEs?

这 "trick" 称为链接 - 将所有已编译的模块和库一起加载到可执行文件中。在您的情况下,您可以手动执行此操作:

g++ -c a.cpp -o a.o  // compiling a.cpp and producing object file a.o
g++ -c main.cpp -o main.o // compiling main.cpp and producing object file main.o
g++ main.o a.o -o myprog // linking all object files together with system libraries and producing executable myprog

对于不同的编译器,命令可能看起来不同,但过程是相同的。当然,您不想一次又一次地键入所有内容,因此您希望将其自动化。 IDE 或 makefile 为您所做的,没有任何技巧或魔法。

我通过向项目添加一个新的 .cpp 文件来解决这个问题,该文件由 Xcode 自动链接到相应的 .hpp 文件。