简体   繁体   中英

Need some help compiling “Hello World” in g++

I recently took the plunge into Debian and wanted to begin translating my code over from visual studio to vim/make/G++.

I'm running Debian wheezy and have installed G++ 4.7.2 (came with debian, can't change it - not enough download quota). I've created a file main.cpp and placed the following into it:

#include <iostream>

int main(){
    std::cout << "hello world" << std::endl;
    return 0;
}

I cd 'd into the directory of that file and ran g++ main.cpp -o hello , which didn't produce any errors or outputs. Then, when I type . hello . hello I get this error:

bash: .: hello: cannot execute binary file

I tried running chmod 777 hello thinking this might be a permission problem but that didn't help either. I'm thinking I might have inadvertently produced an object file instead, but I don't know how to check..

. hello

tells the bash shell to run the hello script in the context of the current shell (ie, it tries to source the script), which is why bash is giving you an error. Methinks you meant to execute:

./hello

It's not actually bash telling your you file isn't executable, rather it's telling you it cannot interpret that binary file as a script. The chmod is irrelevant here because successfully generated executables out of the gcc toolchain are already executable.

For more details on bash sourcing, see the man page, relevant section copied below:

. filename [arguments]
source filename [arguments]

Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename.

If filename does not contain a slash, file names in PATH are used to find the directory containing filename.

The file searched for in PATH need not be executable. When bash is not in posix mode, the current directory is searched if no file is found in PATH.

If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched.

If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged.

The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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