Problem with running c program on mac? - c++

I'm a total beginner in C programming so please bear with me. I have just started today and wanted to write a short program - well at least a small script that would just print out a line of text. Now here's what I did in order to achieve this:
I downloaded vim text editor and wrote this few lines of code:
#include <stdio.h>
int main(void)
{
printf("This is some text written in C \n");
return 0;
}
I saved it as inform.c and compiled it using "cc inform.c" command.
In the end I got a.out file but when I'm trying to run it says:
-bash: a.out: command not found
Can someone tell what I'm doing wrong here and point me in the right direction? Thanks.

Bash can't find your command because the current directory is not usually in the path.
Try:
$ ./a.out

It's a basic one.
on Mac, you need to specify were your executable is.
when you type a.out, the system look for the command in /usr/bin and other synstem binaries folders.
to be more precise type ./a.out
which basically says : "in this directory, command a.out"
you should also add directly the classical signature of main which is :
int main(int argc, char ** argv);

Related

C++, Nothing in the output [duplicate]

This question already has answers here:
Why do I get no output for very simple Hello World program?
(7 answers)
Closed 6 months ago.
I am new to C++ and coded my first main.cpp but I got an error, not exactly an error, it is a logical error, I guess because I wrote the following code:
#include <iostream> // including the iostream
using namespace std; // using the std namespace
int main() { // starting the main function
cout << "Hello World!" << endl; // My favorite line of code in all the of languages
return 0; // returning 0 to stop the function execution
}
In the terminal I expected
C:\Users\DELL\Desktop> g++ main.cpp
Hello World!
C:\Users\DELL\Desktop>
But it is just showing:
C:\Users\DELL\Desktop> g++ main.cpp
C:\Users\DELL\Desktop>
No output is coming, but when I try in Code::Blocks, it is working just fine! In vscode terminal, the same problem but when I run the file, it is working again! Why is it not working? I tried it in Command Prompt, installed the Windows Terminal, and tried it in that also (keeping the terminal as Command Prompt, cause I don't know what PowerShell is and how to use it) but any method is not working.
Please tell me what to do, I am new to c++ and know only some things amount it.
The command g++ main.cpp creates the file a.out or a.exe. After that file is created you need to run it by the command ./a.out on Linux and Mac or a.exe on Windows.
It's pretty simple, after g++ "file.cpp", you get an output file in your current working directory, which is the executable. C++ is compiled, not interpreted.
That output file is the executable, which by default will be "a.out", with gcc/g++. You can use the option "-o" to specify the output directory.
g++ main.cpp will compile the file and produce a.exe, you just need to type a.exe in the terminal and it will print Hello World!.

Syntax error: "(" unexpected

I am trying to compile code using gcc and run the executable, but it is throwing error:
gcc somefile.c -o somefile
compilation goes through successfully. But, when I try to execute it:
$sh somefile
It results in: Syntax error: "(" unexpected. Among the output files, I dont see somefile.o, but instead, I see somefile.c~
The contents of the file:
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("hi");
}
Context: I am new to programming in linux, and wanted to start out with simple programs. I am running ubuntu 64 bit on a virtual machine, with gcc, g++, etc installed. After that I created a sample file as mentioned above ("somefile.c"), and tried the steps mentioned above, but could not execute. My goal is to compile and execute a sample C or Cpp code on ubuntu using gcc or g++. Please help.
your somefile is executable binary, it's not shell script. you should execute it by:
$./somefile
To execute file you just have to do
$./somefile
sh is used when you've to execute a shell script

Why would I get a syntax error near unexpected token? Command line arguments?

Here is the code I have- not sure why I am getting this error message:
$ ./main.cpp "hello" "is"
./main.cpp: line 4: syntax error near unexpected token `('
./main.cpp: line 4: `int main(int argc, char *argv[]){'
It compiles fine in g++, but when I run it, I get the above error. Any idea why? Here is my complete code..
#include <iostream>
#include <fstream>
int main(int argc, char *argv[]){
for(int i = 0; i < argc; i++){
std::cout << argc << " : " << argv[i] << '\n';
}
if (argc != 2){
std::cout << "\nUSAGE: 2 command line arguments please." << std::endl;
std::cout << "\n (1) Input file with raw event scores.\n (2) Output file to write into.";
}
// open the font file for reading
std::string in_file = argv[1];
std::ifstream istr(in_file.c_str());
if (!istr) {
std::cerr << "ERROR: Cannot open input file " << in_file << std::endl;
}
return 0;
}
You have to run the compiled program, not the source code:
$ g++ -o main main.cpp
$ ./main "hello" "is"
3 : ./main
3 : hello
3 : is
USAGE: 2 command line arguments please.
   (1) Input file with raw event scores.
   (2) Output file to write into.ERROR: Cannot open input file hello
Your example is trying to execute C++ code as a shell script, which isn't going to work. As you can see from the output of my test run of your program here, you still have some bugs to work out.
As both the other answers say, you're running it as a shell script, implicitly using /bin/sh.
The first two lines starting with # are treated by the shell as comments. The third line is blank, and does nothing. The fourth line is interpreted as a command int, but parentheses are special to the shell, and are not being use correctly here. There probably isn't an int command in your $PATH, but the shell doesn't get a chance to report that because it chokes on the syntax error.
None of these details are particularly important; the problem is that you're executing the program incorrectly. But it might be interesting to see why those specific error messages are printed.
And it appears that you've done something like chmod +x main.cpp; otherwise the shell would have refused to try to execute it in the first place. Making a C++ source file executable isn't going to cause any real harm (as long as it's readable and writable), but it's not at all useful, and as you've seen it delayed the detection of your error. If you do chmod -x main.cpp, and then try ./main.cpp again, you'll get a "Permission denied" error instead.
As Carl's answer says, you need to execute the executable file generated by the compiler, not the C++ source file. That's why there's a compiler. The compiler (well, actually the linker) will automatically do the equivalent of chmod +x on the executable file it generates.
The file command will tell you what kind of file something is, which affects what you can do with it. For example, using your code on my system, after running g++ main.cpp -o main:
$ file main.cpp
main.cpp: ASCII C program text
$ file main
main: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=0xacee0dfd9ded7aacefd679947e106b500c2cf75b, not stripped
$
(The file command should have recognized main.cpp as C++ rather than as C, but sometimes it guesses wrong.)
"ELF" is the executable format used by my system; the file contains executable machine code plus some other information. The pre-installed commands on the system use the same format.
The details may differ on your system -- and will differ substantially on non-Unix-like systems such as MS Windows. For example, on Windows executable files are normally named with a .exe extension.
The compiler, by default, creates an executable called "a.out", so you want to do:
$ a.out "hello" "is"
Typing "./main.cpp" is trying to execute the C++ source file, probably as a shell script

Error when running OpenNI 2 class ( gcc 4.7.2 / ubuntu 12.10 )

I'm trying to compile an run a very basic program given below (test.cpp) which calls the OpenNI class. You can see the files and dirs they're in here. Sorry that some characters screws up a little bit in the browser's encoding. I'm using the linux command: tree, if you know a better command tell me and I will update it.
File Structure
I'm following the guide here, see "GCC / GNU Make".
#include < stdio.h >
#include < OpenNI.h >
using namespace openni;
int
main ( void )
{
Status rc = OpenNI::initialize();
if (rc != STATUS_OK)
{
printf("\nInitialize failed\n%s\n", OpenNI::getExtendedError());
return 1;
}
printf("Hello, world!\n");
return 0;
}
Here is what I'm running in the command line to compile it (gcc 4.7.2):
gcc test.cpp -I../OpenNI-2.0.0/Include -L/home/evan/Code/OpenNi/Init -l OpenNI2 -o test
This works fine but when I run ./test I get the following error:
Initialize failed
DeviceDriver: library handle is invalid for file libOniFile.so
Couldn't understand file 'libOniFile.so' as a device driver
DeviceDriver: library handle is invalid for file libPS1080.so
Couldn't understand file 'libPS1080.so' as a device driver
Found no valid drivers in './OpenNI2/Drivers'
Thanks, any help would be much appreciated.
Instructions from your guide says, that
It is highly suggested to also add the "-Wl,-rpath ./" to your linkage command. Otherwise, the runtime linker will not find the libOpenNI.so file when you run your application. (default Linux behavior is to look for shared objects only in /lib and /usr/lib).
It seems you have exactly this problem -- it can not find some libraries. Try to add proper rpath (seems to be /home/evan/Code/OpenNi/Init/OpenNI2/Drivers in your case) to your compilation string.
I had the same issue after compiling this little "Hello World" with Eclipse and trying to run it in the command line.
The "Wl,-rpath=./" thing did not work for me.
As also discussed here it worked for me after setting some env. variables before execution:
export LD_LIBRARY_PATH="/path/to/OpenNI2:$LD_LIBRARY_PATH"
export OPENNI2_DRIVERS_PATH="/path/to/OpenNI2/Drivers"
export LD_LIBRARY_PATH="/path/to/OpenNI2/Drivers:$LD_LIBRARY_PATH"
Somewhere I got the info that the first two lines should be enough but it was the third line which is important. I does also work just with the third line.

What is a 'shebang' line?

Currently I'm trying to start programming on my new Mac. I installed TextWrangler, and chose C++ as my language of choice; since I have some prior knowledge of it, from when I used Windows.
So, I wrote the ever so common "Hello World" program. Although, when I tried to run it, I got an error:
"This file doesn’t appear to contain a valid ‘shebang’ line (application error code: 13304)"
I tried searching the error code to find out how to fix this, but I couldn't find anything.. I have no idea what a 'shebang' line is... Can someone help me out?
You need to compile it with a compiler first. I assume you tried to run the source file like ./source but C++ doesn't work this way.
With some compilers however, you can provide a shebang-line as the first line of the source file (the #! is known as shebang or crunchbang, hence the name), like so:
#!/path/to/compiler
So that the shell knows what application is used to run that sort of file, and when you attempt to run the source file by itself, the compiler will compile and run it for you. That's a compiler-dependent feature though, so I recommend just plain compiling with G++ or whatever Macs use to get an executable, then run that.
While I wouldn't recommend it for regular C++ development, I'm using a simple shell script wrapper for small C++ utilities. Here is a Hello World example:
#if 0 // -- build and run wrapper script for C++ ------------------------------
TMP=$(mktemp -d)
c++ -o ${TMP}/a.out ${0} && ${TMP}/a.out ${#:1} ; RV=${?}
rm -rf ${TMP}
exit ${RV}
#endif // ----------------------------------------------------------------------
#include <iostream>
int main(int argc, char *argv[])
{
std::cout << "Hello world" << std::endl;
return 0;
}
It does appear that you are trying to run the source file directly, however you will need to compile using a C++ compiler, such as that included in the gcc (GNU Compiler Collection) which contains the C++ compiler g++ for the Mac. It is not included with the Mac, you have to download it first:
from http://www.tech-recipes.com/rx/726/mac-os-x-install-gcc-compiler/ : "To install the gcc compiler, download the xcode package from http://connect.apple.com/. You’ll need to register for an Apple Developer Connection account. Once you’ve registered, login and click Download Software and then Developer Tools. Find the Download link next to Xcode Tools (version) – CD Image and click it!"
Once it's installed, if you are going for a quick Hello World, then, from a terminal window in the directory of your source file, you can execute the command g++ HelloWorld.cpp -o HelloWorld. Then you should be able to run it as ./HelloWorld.
Also, if you're coming from a Visual Studio world, you might want to give Mono and MonoDevelop a try. Mono is a free implementation of C# (and other languages), and MonoDevelop is an IDE which is very similar to Visual Studio. MonoDevelop supports C# and other .NET languages, including Visual Basic .NET, as well as C/C++ development. I have not used it extensively, but it does seem to be very similar to VS, so you won't have to learn new everything all in a day. I also have used KDevelop, which I liked a lot while I was using it, although that's been a while now. It has a lot of support for GNU-style development in C/C++, and was very powerful as I recall.
Good luck with your endeavors!
Links:
Mono: http://mono-project.com/Main_Page
MonoDevelop: http://monodevelop.com/
KDevelop: http://kdevelop.org/
shebang is http://en.wikipedia.org/wiki/Shebang_%28Unix%29.
not sure why your program is not running. you will need to compile and link to make an executable.
What I find confusing (/interesting) is C++ program giving "Shebang line" error. Shebang line is a way for the Unix like operating system to specify which program should be used to interpret the rest of the file. The shebang line usually points to the path of the interpreter. C++ is a compiled language and does not have interpreter for it.
To get the real technical details of how shebang lines work, do a man execve and get that man page online here - man execve.
If you're on a mac then doing something like this on the commandline:
g++ -o program program.cpp
Will compile and link your program into an executable called program. Then you can run it like:
./program
The reason you got the 'shebang' error is probably because you tried to run the cpp file like:
./program.cpp
And the shell tries to find an interpreter to run the code in the file. Because this is C++ there is no relevant interpreter but if your file contains Python or Bash then having a line like this
#!/usr/bin/python
at the 1st line in your source file will tell the shell to use the python interpreter
The lines that start with a pattern like this: #!/.../.../.. is called a shebang line. In other words, a shebang is the character sequence consisting of the characters number sign and exclamation mark (#!).In Unix-like operating systems, when a text file with a shebang is used as if it is an executable, the program loader mechanism parses the rest of the file's initial line as an interpreter directive. The loader executes the specified interpreter program, passing to it as an argument the path that was initially used when attempting to run the script, so that the program may use the file as input data.