Cannot start make using stdlib C ++ system call

I have the following C ++ code

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

The following is reported:

Make cmd-make -C / home / hamiltont / temp / make: Enter the directory /home/hamiltont/temp' make: *** No targets. Stop. make: Leaving directory /home/hamiltont/temp' make: *** No targets. Stop. make: Leaving directory /home/hamiltont/temp' make: *** No targets. Stop. make: Leaving directory / home / hamiltont / temperature

However, doing this manually works fine in several ways, for example.

 [ 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 
+4
source share
1 answer

Are you creating a makefile from your C program? The only reason I could imagine is the error message.

  make: *** No targets.  Stop 

Error play

Here is how I could generate this message:

 #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; } 

This is expected to print:

  make: *** No targets.  Stop

I say predictably because the Makefile will be empty! This is because IO is buffered ...

Fixed version

So, I close the file before calling system() , which flushes the buffer ( fflush() also does the trick):

 #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; } 

Output:

  echo Done.
 Done

I used the C IO functions for clarity, but the same rules apply to <iostream> .

+6
source

All Articles