无法使用C++ stdlib系统调用运行make命令

4

I've got the following code in C++

  if (should_run_make) {
    std::string make = "make -C ";
    make.append(outdir);
    std::cout << "Make cmd is " << make << std::endl;
    system(make.c_str());
  }

这里报告如下:

Make命令是make -C /home/hamiltont/temp/ make: 进入目录 /home/hamiltont/temp' make: *** 没有指定目标. 停止. make: 离开目录/home/hamiltont/temp'

然而,手动执行该命令却可以以多种方式正常工作。
[hamiltont@4 generator]$ make -C /home/hamiltont/temp/
make: Entering directory `/home/hamiltont/temp'
g++ -O3 -I/usr/include/openmpi-x86_64 -L/usr/local/lib -L/usr/lib64/openmpi/lib -lmpi -lmpi_cxx -lboost_serialization -lboost_mpi  stg_impl.cpp -o impl
make: Leaving directory `/home/hamiltont/temp'

[hamiltont@4 generator]$ cd /home/hamiltont/temp/
[hamiltont@4 temp]$ make
g++ -O3 -I/usr/include/openmpi-x86_64 -L/usr/local/lib -L/usr/lib64/openmpi/lib -lmpi -lmpi_cxx -lboost_serialization -lboost_mpi  stg_impl.cpp -o impl

完全删除了“all”这个词,但是我看到的行为都一样。更新问题以匹配。 - Hamy
@MatsPetersson,我不知道,如果是这种情况,进入目录会失败或者抛出错误的命令调用,而不仅仅是找不到make文件吗? - Fantastic Mr Fox
2
请确保您没有使用任何shell函数或别名。type make应该可以正常工作。 - Zan Lynx
我怀疑这是一个环境问题。由system()调用的shell的PATH可能不同...您可以尝试使用system("which make")并将其与shell的手动输出进行比较。您还可以尝试检查shell环境变量、别名、函数,它们可以自定义make的行为,提供额外的标志或更改行为。 - Tony Delroy
1
还可以尝试在您的system()调用中添加“-d”标志。这应该会产生大量的调试输出。 - Zan Lynx
显示剩余3条评论
1个回答

6

您是否在C程序中生成makefile?这是我能想到的唯一导致特定错误消息的原因。

make: *** No targets. Stop. 

重现错误

以下是我如何生成该消息:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    FILE *fp = fopen("Makefile", "w");
    fputs("all:\n\techo Done.\n", fp);
    system("make");
    fclose(fp);
    return 0;
}

可以预见的是,输出如下:

make: *** 没有指定目标并停止。

这是因为Makefile为空!这是因为IO被缓冲...

修复版本

所以,在调用system()之前,我关闭文件,这样就可以刷新缓冲区(fflush()也可以):

#include <stdio.h>
#include <stdlib.h>
int main()
{
    FILE *fp = fopen("Makefile", "w");
    fputs("all:\n\techo Done.\n", fp);
    fclose(fp);
    system("make");
    return 0;
}

输出:

echo 完成了。
完成了。

我使用C的IO函数来提高清晰度,但同样的规则适用于<iostream>


我在使用std::ofstream来构建Makefile,而且我遵循了其他地方的建议,让析构函数关闭流比手动调用close更好:-)。手动调用close解决了这个问题! - Hamy
3
作为另一种选择,如果您使用大括号 {...} 将代码包含起来并将流定义为块作用域变量,仍然可以使用析构函数关闭文件。 - Dietrich Epp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接