C++ .cpp中.o文件调用函数的编译问题

C++ .cpp中.o文件调用函数的编译问题,c++,c,makefile,C++,C,Makefile,我有一个temp1.c文件,它有一个函数 int add(int a, int b){ return (a+b); } 和temp1.h文件 int add(int,int) 我通过编译从中创建了.o文件 g++-o temp1.o-c temp1.cpp 现在我必须使用temp2.cpp中的add函数,该函数放在不同的目录中。我已经做了 #include "temp1.h" int main(){ int x = add(5,2); } 我必须用temp1.o编译temp2.cpp,以便

我有一个temp1.c文件,它有一个函数

int add(int a, int b){ return (a+b); }
和temp1.h文件

int add(int,int)
我通过编译从中创建了.o文件

g++-o temp1.o-c temp1.cpp

现在我必须使用temp2.cpp中的add函数,该函数放在不同的目录中。我已经做了

#include "temp1.h"
int main(){
int x = add(5,2);
}
我必须用temp1.o编译temp2.cpp,以便创建一个可以调用add函数的temp2.exe。如何编译它?

像这样:

 g++ temp2.cpp temp1.o -o temp2.exe
temp2: temp1.o temp2.o
     g++ temp1.o temp2.o -o temp

temp1.o: temp1.cpp
     g++ -c temp1.cpp -o temp1.o

temp2.o: temp2.cpp
     g++ -c your/path/to/temp2.cpp -o temp2.o

@LuchianGrigore I M SAARI OLD Habbitars最好使用
$(CXX)
。然后,您可以在Makefile的开头定义正在使用的编译器,而不是影响对gcc的依赖性。@moshbear OP专门针对g++(在他的问题中)提出了要求。但你是对的,如果它是一个生产级的makescript,我会写更多的变量和更好的规则。我错过了那部分。另外,由于使用的操作系统是Windows(由于temp2.exe),可执行目标(和
-o
参数)应该从
temp2
更改为
temp2.exe
@moshbear afaik,默认为.exe on(mingw和cygwin)。我必须从temp2.cpp创建.o,然后从temp2.exe创建temp2.exe吗?在哪里使用temp1.o?