这个程序是一个“grader”程序,我只是要求用户输入 txt 文件的名称和处理 txt 文件并获取其信息的 .cpp 源文件。然后,我将源文件与 txt 文件一起编译,输出另一个文本文件。然后将这种新纺织品与预期产量进行比较(我也得到了预期产量)。
系统函数允许用户从 C 程序运行 UNIX 命令。当我尝试编译用户提供的源文件时
我收到一条错误消息
"_main", referenced from: implicit entry/start for main executable.
clang: error: linker command failed with exit code 1 (use -v to see invocation)
sh: ./myProg: No such file or directory
我正在编译的教授提供的源文件有一个如下所示的函数:
#include <stdio.h>
#include <stdlib.h>
#define MAX_VALUES 3
#define OUTPUT_LINES 5
int notmain(int argc, char **argv)
{
/*
* argv is just the file name
*/
//printf(argv[1]);
int values[MAX_VALUES];
int i, j;
FILE *inputFile;
char name [20]="input.txt"; // I have included this piece of code to see if there is a correct output from the source file provided by the user.
if ( (inputFile = fopen(name, "r") ) == NULL) {
printf("Error opening input file.\n\n");
exit(1);
}
for(i = 0; i < MAX_VALUES; i++)
fscanf(inputFile, "%d", &values[i]);
for(i = 0; i < OUTPUT_LINES; i++){
for (j=0; j < MAX_VALUES; j++)
printf("%d ", values[j]*(i+1) + j);
printf("\n");
}
return 0;
}
我编写的代码如下所示: 该代码从用户处获取信息,然后对其进行编译。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUM_LINES 5
int main(){
char srcfile[200];
char inpfile[200];
char resultfile[200];
printf("Please enter the name of the source file: \n");
scanf("%s",srcfile);
printf("Please enter the name of the input file: \n");
scanf("%s",inpfile);
printf("Please enter the name of the expected result file: \n");
scanf("%s",resultfile);
char test1 [100]="gcc -o myProg ";
char test2 [100]="./myProg ";
strcat(test2,inpfile);
strcat(test2," > ");
strcat(test2,resultfile);
strcat(test1,srcfile);
printf("%s\n",test1); //these are just tests
printf("%s",test2); //these are just tests
if (system(test1)) {
printf("There is an error compiling the program ");
}
if (system(test2)!= 0) {
printf("There is an error running the executable");
}
return 0;
}
如果您正在寻找解决方案,我已将其发布在答案中
最佳答案
您尝试编译的文件没有 main
函数,该函数是 C 程序的入口点。这意味着实际上不可能将该文件单独构建为可执行文件。
如果函数名称应为 notmain
,那么您必须编写另一个具有 main
函数并调用 notmain< 的源文件
。第二个 main
将属于您的程序正在编译的可执行文件,而不是您的程序。您将拥有三个源文件:
- 您的评分器程序,用于处理编译。
一种有效执行以下操作的包装文件:
int main(int argc, char *argv[]) { notmain(argc, argv); }
- 最后是要评分的项目。
您还需要extern
notmain
函数或提供一个 header 来共享它。然后,您的评分器程序将编译包装器 main
和要一起评分的源文件。
关于c - 使用系统函数运行另一个.cpp文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36110295/