簡體   English   中英

C ++從文本文件執行代碼

[英]C++ executing a code from a text file

標題說明了一切。 像編譯器,但不一樣。 我希望代碼的某些部分可以從C ++的外部源中執行。 而且我不知道這是否可能實現,如Javascript,Python等。

假設我有一個名為sample.txt的文本文件,如下所示:

int a = 10, c;
cin >> c;
cout << a + c;

然后,我將在main()函數中調用文本文件並編譯.exe文件。 當我運行它時,它是否有可能動態地表現為好像文件中的代碼已嵌入其中並寫入10+輸入? 應該更改源文件,並且下次運行時將應用不同的結果。 順便說一下,這只是示例代碼,我可能想運行一些for / while循環以及if條件等。

PS:我知道如何讀取文件並將其分配為整數或將其寫入屏幕,這不是我想要的。 我需要通過編譯功能。 謝謝。

有兩種方法。

分叉命令行編譯器,並分叉運行結果,並通過STDIN / STDOUT傳遞輸入和輸出

(雖然我意識到您是從C ++調用程序中請求的,但為了簡單起見,我在bash中演示了這個想法。)

文件: run_it.sh

#!/bin/bash
set -e  # Bail on the first error

FN_IN=./sample.txt
FN_WRAPPED=./wrapped.cc
FN_EXE=./wrapped
CC=g++

# Wrap the fragment in a full C++ program and compile it.
function build_wrapper () {
  cat > $FN_WRAPPED <<'EOF'
#include <iostream>

using namespace std;

int main(int argc, char **argv) {
EOF
  cat $FN_IN >> $FN_WRAPPED 
  cat >> $FN_WRAPPED <<'EOF'
return 0;
}
EOF
  $CC -o $FN_EXE $FN_WRAPPED 
}

# Run the wrapper, passing input through STDIN and reading the output from STDOUT.
function run () {
  local IN=$1
  echo $IN | $FN_EXE
}

# Remove the wrapper (both code and compiled).
function clean_up () {
  rm -f $FN_WRAPPED $FN_EXE
}

build_wrapper

IN=24
OUT=$(echo "$IN" | $FN_EXE)
echo "Result = $OUT"

echo "Another result = $(run 16)"

clean_up

$ ./run_it.sh

Result = 34
Another result = 26

使用類似LLVM的方法在過程中編譯函數並調用它

這種方法非常強大,但是也有些牽扯。

簡而言之,您想要

  1. sample.txt讀取到內存中。
  2. 將其編譯為函數。
  3. 調用該函數。

一些可能有用的鏈接:

編譯后的C ++程序僅包含執行編譯后的源代碼所需的機器指令,語言標准未指定任何機制供用戶在運行時生成其他機器指令。

為了提供腳本功能(響應輸入文本的解析生成程序流的能力),您必須提供解析器和執行引擎。

int main()
{
    std::string cmd;
    int op1, op2;
    while (cin >> cmd >> op1 >> op2) {
       if (cmd == "add")
           std::cout << op1 + op2 << "\n";
       else if (cmd == "sub")
           std::cout << op1 - op2 << "\n";
       else
           std::cerr << "error\n";
    }
}

首先,許多解釋語言都是用C或C ++編寫的,因此通常可以將它們構建為庫,然后將其合並到應用程序中,以便程序可以調用它們以提供嵌入式腳本語言。 這類語言的常見示例是LuaPythonJavaScript 然后,您的程序可以將要執行的代碼傳遞給解釋器。

編寫自己的lua解釋器可能如下所示:

#include <iostream>
#include <string>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

bool get_input(std::string& in)
{
  bool result;
  do {
    std::cout << "lua> " << std::flush;
    result = std::getline(std::cin, in);
  } while (result && in.empty());
  return result;
}

int main (void) {
  lua_State *L = lua_open();   // open lua
  luaL_openlibs(L);            // open standard libraries

  std::string in;
  while (get_input(in)) {
    if (in.empty())
        continue;

    int error = luaL_loadbuffer(L, in.c_str(), in.size(), "line") ||
                lua_pcall(L, 0, 0, 0); 
    if (error) {
      std::cerr << lua_tostring(L, -1) << '\n';
      lua_pop(L, 1);  // remove the error message from the stack
    }
  }

  lua_close(L);
}

在Linux下:

$ g++ -Wall -O3 -o mylua mylua.cpp -I/usr/include/lua5.1 -llua
$ ./mylua
lua> print("hello")
hello
lua> error
[string "line"]:1: '=' expected near '<eof>'
lua> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM