In Linux I am writing the simplest c++ program just to make sure everything can execute before writing more advanced code. I am simply trying to run a c++ program that writes output to the screen however when I run the program, the same error comes up "Badly placed ()'s".
Here is my program fork.cpp:
#include <iostream>
#include <string>
#include <sys/types.h> // certain libraries included for later code, more specifically using a fork command
#include <unistd.h> // that I am also having trouble with
#include <stdlib.h>
int main ()
{
cout << "Hello World";
return 0;
}
The program is included in a Makefile I have so I compile with "make fork.cpp" then run with ./fork.cpp
***I have tried eliminating/moving the parenthesis after "int main" and still no help. I have also tried adding shell-script headers, more specifically the shell I am currently running in (TCSH). Any suggestions?
When you attempt to "run" a plain text file, it is interpreted as a sequence of commands to the command interpreter (that is, as a shell script). The lines that begin with # are treated as comments by the shell, and the line "int main ()" is a syntax error.
Compile with g++ -W -Wall -Wextra -pedantic -o fork fork.cpp, then run with ./fork
The program was written using emacs, if that changes anything...When I tried the compile command you suggested it gave me this:
sirius: g++ -W -Wall -Wextra -pedantic -o fork fork.cpp
fork.cpp: In function ‘int main()’:
fork.cpp:11:3: error: ‘cout’ was not declared in this scope
fork.cpp:11:3: note: suggested alternative:
/usr/include/c++/4.6/iostream:62:18: note: ‘std::cout’
Then when I ran it using "./fork" it says "command not found".
./fork doesn't work because it failed to compile and no executable file was created. Names in the standard library is often placed inside the std namespace. If you add std:: in front of cout it should work.
#include <iostream>
#include <string>
#include <sys/types.h> // certain libraries included for later code, more specifically using a fork command
#include <unistd.h> // that I am also having trouble with
#include <cstdlib> // In C++ use this rather than stdlib.h
int main ()
{
std::cout << "Hello World"; // add std:: before standard library symbolsreturn 0;
}