c++用argv字符串用法(cygwin编译器编译两个.c源文件用法)
本文主要总结在.exe可执行程序启动时,传入字符串*argv[],其中采用的编译器是cygwin,编写代码用notepad工具。下面是一个实例,是用cygwin的gcc编译出可执行程序mainHello.exe,当在命令行输入 mainHello.exe -start 命令时,打印出 this is a start command! ,当在命令行输入 mainHello.exe -stop 命令时,打印出 this is a stop command! 。具体的代码步骤如下所述。
1.1首先新建一个hello.h和hello.c文件,然后分别在hello.h和hello.c文件,分别输入如下代码。
hello.h头文件,输入如下代码:
#ifndef HELLO_H
#define HELLO_H
#ifdef __cplusplus
extern "C" {
#endif
extern void hello(const char* name);
#ifdef __cplusplus
}
#endif
#endif
hello.c源文件,输入如下代码:
#include <stdio.h>
void hello(const char* name)
{
printf("Hello%s!\n", name);
}
1.2新建一个mainHello.c文件,并且按下面要求输入代码。
mainHello.c源文件,输入如下代码
#include "hello.h"
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
for(int i=1;i<argc;i++)
{
if(strcmp(argv[i],"-start")==0)
{
//printf("start123\n");
hello("this is a start command!");
}
else if(strcmp(argv[i],"-stop")==0)
{
//printf("stop123\n");
hello("this is a stop command!");
}
}
return 0;
}
1.3在cygwin下,输入如下命令行,编译mainHello.c和hello.c源文件,生成mainHello.exe可执行程序,如下图所示:
gcc mainHello.c hello.c -o mainHello.exe
1.4在cygwin下,输入如下命令行,执行mainHello.exe可执行程序,如下图所示:
./mainHello.exe -start
有上面内容可知,改程序在cygwin下输入mainHello.exe -start命令行时,可以打印出内容Hellothis is a start command!!。
参考内容:
https://blog.****.net/naibozhuan3744/article/details/80535262