1 Star 0 Fork 0

蝎子莱莱xo/cpp_projects

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
compiler.hpp 2.46 KB
一键复制 编辑 原始数据 按行查看 历史
lmx-xo 提交于 1年前 . 顶层makefile
#pragma once
#include "../comm/util.hpp"
#include "../comm/log.hpp"
namespace ns_compiler
{
using namespace ns_util;
using namespace ns_log;
class Compiler
{
// 该类只提供方法
public:
Compiler()
{
}
~Compiler()
{
}
static bool Compile(const string &file_name)
{
pid_t pid = fork();
if (pid < 0)
{
LOG(ERROR) << "内部错误,创建子进程失败" << "\n";
return false;
}
else if (pid == 0)
{
//将权限掩码清0,保证权限的正确设置
umask(0);
// 子进程,负责调用g++编译器进行编译
// 在编译之前,需要打开保存编译错误信息的临时文件,并将stderr重定向到该文件
int _stderr = open(PathUtil::CompileError(file_name).c_str(), O_CREAT | O_WRONLY, 0644);
if(_stderr < 0)
{
LOG(WARNING) << "没有成功成成stderr文件" << "\n";
exit(0);
}
//重定向标准错误到_stderr
dup2(_stderr, 2);
//调用g++完成编译工作
//g++ -o target src -std=c++11
//最后一个参数后面一定要跟一个nullptr
//execlp第一个参数是替换调用哪个程序,后面的参数才是如何调用
//需要加上编译选项-D COMPILER_ONLINE,条件编译
execlp("g++", "g++", "-o", PathUtil::Exe(file_name).c_str(),\
PathUtil::Src(file_name).c_str(), "-D", "COMPILER_ONLINE", "-std=c++11", nullptr);
LOG(ERROR) << "启动g++编译器失败,可能是参数错误" << "\n";
//程序替换失败
exit(2);
}
else
{
// 父进程
waitpid(pid, nullptr, 0);
//编译是否成功,看对应的文件夹下有没有生成对应的可执行程序
if(FileUtil::IsFileExists(PathUtil::Exe(file_name)))
{
LOG(INFO) << PathUtil::Src(file_name) << " 编译成功" << "\n";
return true;
}
LOG(ERROR) << "编译失败,没有形成可执行程序" << "\n";
return false;
}
}
};
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/lmx-xo/cpp_projects.git
git@gitee.com:lmx-xo/cpp_projects.git
lmx-xo
cpp_projects
cpp_projects
master

搜索帮助