简体   繁体   English

执行C ++二进制文件而不以`。/`结尾

[英]Execute C++ binary without leading `./`

Suppose I have a file called A.cpp. 假设我有一个名为A.cpp的文件。

I used argc and argv in main to make it a terminal application, that means I want the program to work like this: 我在main中使用argc和argv使其成为终端应用程序,这意味着我希望程序像这样工作:

terminal> program [options] [input]

Given I compile it like this: 鉴于我这样编译:

g++ -std=c++11 -o program A.cpp

When I wrote 当我写

program [options] [input] 程序[选项] [输入]

in windows, it worked just fine, but in ubuntu I have to write 在Windows中,它工作正常,但是在ubuntu中,我必须编写

terminal> ./program [options] [input]

is there a way to execute it without this " ./ " ? 没有此“ ./”,有没有办法执行它?

grep works in ubuntu just like that and without the " ./ ", and I wanted A.cpp to run just like grep. grep在ubuntu中可以这样工作,并且没有“ ./”,我希望A.cpp像grep一样运行。

Depending on your shell, and possibly its configuration, it may already work. 根据您的外壳以及可能的配置,它可能已经起作用。

Assuming you have actually tried, and it does not, then you need to put your program in a directory that is on your $PATH . 假设您实际上已经尝试过,但是没有尝试过,那么您需要将程序放在$PATH上的目录中。

$ echo $PATH

to see a colon ( : ) separated list of candidate directories, such as /usr/local/bin , to where you could mv it, or alternatively you could put it anywhere you like, and add that to $PATH : 看到一个冒号( : )分隔候选目录,如清单/usr/local/bin ,到了那里你可以mv它,或者你可以把它放在任何你喜欢的,并添加到$PATH

$ mkdir -p ~/my-progs
$ mv prog ~/my-progs
$ echo 'export PATH="$HOME/my-progs:$PATH"' >> ~/.bashrc
$ source ~/.bashrc

assuming you are using bash (check echo $SHELL ). 假设您正在使用bash(请检查echo $SHELL )。

I think you have to add your directory of executable to the PATH variable of your shell (this may change between some shells). 我认为您必须将可执行文件目录添加到Shell的PATH变量中(这在某些Shell之间可能会发生变化)。

export PATH=$PATH:/path/to/dir

If you would like to make it permanent you may need to add this to 如果您想使其永久保存,则可能需要添加到

~/.profile (or ~/.bashrc depends on your shell)

However, personally I prefer creating a shell script to prepare the development environment and run it whenever I need instead of hardcoding these values somewhere in the filesystem. 但是,就我个人而言,我更喜欢创建一个Shell脚本来准备开发环境并在需要时运行它,而不是在文件系统中的某些地方对这些值进行硬编码。 By this way, you can initialize some other variables which may be usefuful for further development plans. 这样,您可以初始化一些其他变量,这些变量可能对进一步的开发计划有用。

You can place your executable program in /usr/bin 您可以将可执行程序放在/ usr / bin中

By example if your program is named myprog you can move it in /usr/bin/myprog, then you can execute it from anywhere by typing 例如,如果您的程序名为myprog ,则可以将其移动到/ usr / bin / myprog中,然后可以通过键入以下内容在任何位置执行它

$ myprog

To give it execution permission if needed : 必要时授予执行权限:

$ sudo chmod +x myprog

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM