调用外部代码
Calling External Codes
是否可以从记事本等外部文件(如果需要,也可以调用 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;
}
- 我收到错误LNK2001:未解析的外部符号(C++代码)
- Python 3.8:运行外部C++代码:无法导入模块
- 如何将外部代码包含在虚幻引擎4 C++项目中
- 如何在不进入 Visual Studio 2015 中的外部库的情况下单步执行我的代码 (F11)
- 引入参数化构造函数后显示 LNK 2019 未解析外部符号的代码错误
- 在下面的代码中,外部块m如何给出输出20
- 在 C++ 中使用 C 代码与外部"C"的问题
- 我正在为学校开发一个小班模板实验室,我的代码无法编译,它给了我一个未解析的外部符号
- 外部 "C" Visual Studio 2015 中的显式类型错误,DLL 测试代码
- 删除外部包含代码库中的删除
- 无法将Android WebView渲染到C 和Java代码之间共享的外部纹理中
- 如何跟踪通过外部代码修改类变量的所有位置
- G++ 自定义任务在外部终端中打开,与 VS 代码内部终端
- 使用 select() 和大量文件描述符的外部代码
- 外部模板如何实际生成代码
- STD ::承诺外部代码,异步取消
- 我应该包括外部库的src代码还是从外部库构建的静态库
- C++外部代码的垃圾回收
- 将外部.asm文件包含到C++代码中
- 在 gcc 中使用数组参数编译外部"c"代码