这是我用 C 编写的代码。我习惯了 Java,因此我不明白 C 编译器如何使用实现的方法找到正确的源文件。
例如,如果我将sample_c1.cpp文件与Main.cpp放在一起,它将转到sample_c1.cpp的on_start()。如果我删除sample_c1.cpp并将sample_c2.cpp与Main.c放在一起,它将转到sample_c2.cpp的on_start()。
这是我的测试程序:
主.c
//no includes to sample_c1.cpp or sample_c2.cpp
void on_start();
void on_stop();
int main(int argc, char* argv[]){
on_start();
return 0;
}
sample_c1.cpp
//this is all i have in the file no class definition no nothing just implementations of the methods
void on_start(){
....
}
void on_stop(){
......
}
sample_c2.cpp
//this is all i have in the file no class definition no nothing just implementations of the methods
void on_start(){
....
}
void on_stop(){
......
}
最佳答案
您的 IDE 告诉编译器*您项目中所有源文件的名称。编译器*同时处理它们。如果它发现您正在调用未在同一源文件中定义的函数,那么它将在其他源文件中查找。如果您有一个名为 sample_c1.cpp
的文件,那么它将在那里查找。如果您有一个名为 sample_c2.cpp
的文件,那么它将在那里查找。如果您有一个名为 travel_back_in_time_and_murder_hitler.cpp
的文件,那么它会在那里查找。
确实没有什么令人兴奋的事情发生。没有像 Java 中那样的“类路径”。只是一堆制作程序的源文件。
* 实际上是链接器,但是编译器和链接器之间的区别超出了这个问题的范围。它基本上只是编译器的另一部分。
关于c++ - 在C和C++中,链接器如何找到具有已实现功能的正确文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32163200/