简体   繁体   English

在运行时进行编译,并在C ++中#include自定义标头

[英]Compiling at runtime and #include custom header in C++

I need to compile and link some code at runtime. 我需要在运行时编译并链接一些代码。 I am using the approach suggested here: https://stackoverflow.com/a/10565120/3038460 我正在使用此处建议的方法: https : //stackoverflow.com/a/10565120/3038460

Basically I am writing my code into a .cpp file and then compiling with 基本上,我将代码写入.cpp文件,然后使用

/usr/bin/g++ -shared mysource.cpp -o libname.so

Everything works fine while I only #include headers from standard libraries. 一切正常,而我仅#include标准库的标头。 But what if I need to use a custom class within the 'dynamic' code? 但是,如果我需要在“动态”代码中使用自定义类怎么办? How can include my own header? 如何包含我自己的标题? The .cpp file is temporary stored in the same location of my binary file and this might be different than the location of my source files. .cpp文件是临时存储在我的二进制文件的同一位置,并且可能与我的源文件的位置不同。 Is there a way to know at runtime where the original source code was located? 有没有办法在运行时知道原始源代码的位置? I doubt. 我怀疑。

Moreover I would like my code to work even if the original source code is not available. 此外,即使原始源代码不可用,我也希望我的代码能够工作。

To clarify, mysource.cpp might look like this: 为了澄清,mysource.cpp可能看起来像这样:

#include <stdlib.h>
#include <vector>
#include "myheader.h"     <---- how can g++ find this file? At runtime,
                                when I create mysource.cpp, I have no idea
                                where myheader.h is located

void f(){
  // Code
}

What's the best solution to solve this problem? 解决此问题的最佳解决方案是什么?

Generate the contents of that header file into the generated source file. 将该头文件的内容生成到生成的源文件中。

Technically, an #include directive is just a directive to include the full contents of a header file in the body of a source file (specifically, at the point where you included it) at compile time. 从技术上讲, #include指令仅是在编译时将头文件的完整内容包括在源文件主体中的指令(特别是在包含该文件的位置)。 You can thus skip the middleman and generate the contents of that header file into your source file before compiling it instead of an #include 因此,您可以跳过中间人,并在编译它之前而不是#include将该头文件的内容生成到源文件中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM