![](/img/trans.png)
[英]Is there a good cross-platform way to include external C++ libraries using CMake?
[英]Simple C++ cross-platform way to execute an external program
什么是一種簡單,優雅,有效的跨平台方式,用C ++執行外部程序並從中獲取返回代碼?
int execute(std::string const &path, std::vector<std::string> const &arguments = {})
{
//...
}
由於我們在繼續執行之前等待被調用的程序完成,因此被調用的程序應該使用我們程序的輸入/輸出/錯誤流。 如果由於多種原因, path
不可執行,只需拋出異常(例如std::invalid_argument
)。
顯然,不要使用system()
。
如果只需要執行一個程序,則生成一個工作線程並擁有該線程調用system
:
void executeProgram(std::string programName) {
system(programName.c_str());
}
void execute() {
string programName = "test.cpp";
std::thread worker (executeProgram, programName);
worker.join(); //wait for the worker to complete
}
如果您需要能夠生成許多程序,則委托工作線程並在完成時連接它們的線程池類可能更有意義。
至少對於命令行應用程序,我使用popen
解決了這個問題.On windows是_popen
但是可以通過定義輕松解決
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.