调用外部代码

Calling External Codes

本文关键字:代码 外部 调用      更新时间:2023-10-16

是否可以从记事本等外部文件(如果需要,也可以调用 cpp 文件)调用例程?

例如我有 3 个文件。主代码.cpp

SubCode_A.cpp <- 不包含在主代码的标头中.cpp

SubCode_B.cpp <- 不包含在主代码的标头中.cpp

MainCode_A.cpp

  #include <iostream>
  using namespace std;
  int main ()
  {
  int choice = 0;
  cin >> choice;
  if (choice == 1)
  {
  "call routines from SubCode_A.cpp;" <- is there a possible code for this?
  }
  else if (choice == 2)
  {
  "call routines from SubCode_B.cpp;" <- is there a possible code for this?
  }
  return 0;
  }

====

==================================

SubCode_A.cpp代码

  {
  if (1) //i need to include if statement :)
        cout >> "Hello World!!";
  }

====

==================================

SubCode_B.cpp代码

  {
  if (1) //i need to include if statement :)
        cout >> "World Hello!!";
  }

在例如 SubCode_A.cpp函数,然后在主源文件中声明此函数并调用它。当然,您必须使用所有源文件进行构建才能创建最终的可执行文件。

你可以只使用 #include 语句。Include 指示编译器在 #include 点插入指定的文件。所以你的代码将是

if (choice == 1)
{
    #include "SubCode_A.cpp"
}
...

而且您不需要SubCode_中额外的牙套吗?cpp 文件,因为它们存在于主代码中.cpp

当然,编译器只会在编译时编译子代码文件中的内容。 对源代码所做的任何未编译的更改最终都不会显示在可执行文件中。

但是中源码 #includes 并不适合非常可读的代码。

你必须编译两个代码,声明一个外部函数(例如 extern void function (int); ,在标头中。编译将包含此标头的两个文件。然后在第三个文件中,您使用它只包含标头。

但是当您在编译中包含所有 3 个文件时,它将起作用。

这篇另一篇文章可能有用:extern关键字对C函数的影响

无法在另一个可执行文件中调用代码。一个应用程序可以通过库或 DLL 公开"api"(应用程序编程接口),该库或 DLL 允许您调用应用程序使用的一些代码。

但是,在编译代码时,编译器需要知道要调用的函数的"指纹":也就是说,它返回什么以及它需要什么参数。

这是通过声明或"原型存根"完成的:

// subcode.h
void subCodeFunction1(); // prototype stub
void subCodeFunction3(int i, int j);
// subcode.cpp
#include <iostream>
void subCodeFunction1()
{
    std::cout << "subCodeFunction1" << std::endl;
}
void subCodeFunction2()
{
    std::cout << "subCodeFunction2" << std::endl;
}
void subCodeFunction3(int i, int j)
{
    std::cout << "subCodeFunction1(" << i << "," << j << ")" << std::endl;
}
// main.cpp
#include "subcode.h"
int main() {
    subCodeFunction1(); // ok
    subCodeFunction2(); // error: not in subcode.h, comment out or add to subcode.h
    subCodeFunction3(2, 5); // ok
    return 0;
}