Compiling c code programatically in linux terminal gcc

杀马特。学长 韩版系。学妹 提交于 2019-12-06 04:38:06

I'm not completely following your logic, put here are some possible problems:

First of all, where do you get the path from; this program may be simpler using command-line arguments than it is how you are doing it.

This means, you declare main as follows in your main file: int main( int argc, char *argv[] )

In this form, argc is the number of arguments passed INCLUDING the file name, and argv[0] is a string holding your file's name.

So, rather than rely on the program to generate the file for you, you do it somewhat like this:

#include "stdlib.h"
#include "stdio.h"
#include "string.h"
int main( int argc, char *argv[] ) {
  if (argc != 3) {
    fprintf( stderr, "Usage: %s %s\n", argv[0], "input_file output_file" );
    fprintf( stderr, "Do not add an extension to output_file.\n" );
    return EXIT_FAILURE;
  }
  unsigned int i = 0;
  for (i = 0; i < strlen( argv[2] ); i++) {
    if (argv[2][i] == '\n' || argv[2][i] == '\0') {
      argv[2][i] = '\0';
      break;
    }
  }
  char format_string[150];
  sprintf( format_string, "gcc.exe -Wall -Wextra -c %s -o %s.o", argv[1], argv[2] );
  char format_string2[150];
  sprintf( format_string2, "gcc.exe %s -o %s.exe", argv[1], argv[2] );
  system( format_string );
  system( format_string2 );
  return EXIT_SUCCESS;
}

With the above program, you just create the input file then pass the inpu file as the first argument and your output to the second one. This file does make two assumptions: input_file exists and the path to gcc is in your enviroment's path variable.

Finally, don't forget that main does NOT need a prototype.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!