error in compiling flex program with g++ - c++

Here is my simple lex file with main function inside it .
I want to compile it using g++ .
%{
#include <iostream>
%}
%%
[ \t] ;
[0-9]+\.[0-9]+ { cout << "Found a floating-point number:" << yytext << endl; }
[0-9]+ { cout << "Found an integer:" << yytext << endl; }
[a-zA-Z0-9]+ { cout << "Found a string: " << yytext << endl; }
%%
main() {
// lex through the input:
yylex();
}
I run following commands on my terminal
lex ex1.l
g++ lex.yy.c -lfl -o scanner
i get following error

cout lives in the std namespace. You need to refer to it as
std::cout
The same applies to endl.
Note, you can say
using std::cout;
using std::endl;
somewhere before using cout and endl names. You should be careful that there is no potential for name clashes when doing this. Use it in limited scopes, and not in header files.

Related

I can't compile the filesystem library

I'm trying to use the filesystem library and it's not working I need help about compiling this.
I tried to change the included file and I updated my compiler but nothing works
here are the inclusions I made
#include <experimental/filesystem>
namespace fs = std::filesystem;
I compile the cpp file with this command
g++ -Wall -c indexation_fichier.cpp
I get this error
indexation_fichier.cpp:5:10: fatal error: experimental/filesystem: No such file or directory
#include <experimental/filesystem>
^~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
and here is my compiler version
g++ (MinGW.org GCC-8.2.0-1) 8.2.0
when I type
g++ --version
I want to know what is wrong and what I need to do to make this library work because I need it for my project.
thanks.
You can either compile your code using -lstdc++fs flag OR like #pete mentioned in the comment: remove experimental, as it is now part of standard C++17.
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main(){
fs::path pathToShow(fs::current_path());
std::cout << "exists() = " << fs::exists(pathToShow) << "\n"
<< "root_name() = " << pathToShow.root_name() << "\n"
<< "root_path() = " << pathToShow.root_path() << "\n"
<< "relative_path() = " << pathToShow.relative_path() << "\n"
<< "parent_path() = " << pathToShow.parent_path() << "\n"
<< "filename() = " << pathToShow.filename() << "\n"
<< "stem() = " << pathToShow.stem() << "\n"
<< "extension() = " << pathToShow.extension() << "\n";
return 0;
}
and then something like g++ -o fs filesystem.cpp will work fine.

Is there a way I can include my files in C++?

Sorry super noob question. I'm new to C++ and any sort of programming in general but I created these programs to read user input and then read what command and file it is. I want to include file a.h but I'm having trouble with it. It's telling me my function main is redefined but when I take it out it spits out more errors. I'm considering maybe an if else statement? Any advice to get me going?
File name tryout.cpp
#include <iostream>
#include <string.h>
#include "a.h"
using namespace std;
int main()
{
string cmd,command,file1,file2;
cout << "prompt<<";
cin >> cmd;
int len = cmd.length();
int temp = cmd.find('<');
command = cmd. substr(0,temp);
cout << "COMMAND: " << command << "\n";
cout << "File Redirection: " << cmd.at(temp) << "\n";
int temp1 = cmd.find('>');
file1 = cmd.substr(temp+1,temp1-temp-1);
cout << "FILE: " << file1 << "\n";
cout << "File Redirection: " << cmd.at(temp1) <<"\n";
file2 = cmd.substr(temp1+1, len-1);
cout << "File: " << file2 <<"\n";
return 0;
}
File name "a.h"
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string cmd,command1,command2,command3;
cout << "prompt<<";
cin >> cmd;
int len = cmd.length();
int temp = cmd.find('|');
command1 = cmd.substr(0,temp);
cout << "COMMAND: " << command1 << "\n";
cout << "PIPE: " << cmd.at(temp) << "\n";
command2 = cmd.substr(temp+1,len-1);
cout << "COMMAND: " << command2 << "\n";
cout << "PIPE: " << cmd.at(temp) << "\n";
command3 = cmd.substr(temp+2,len-2);
cout << "COMMAND: " << command3 << "\n";
return 0;
}
The ".h" suffix is for a "header" file. If you think of a form letter, say from your cell company, at the top is a bunch of stuff telling you the company name, contact, etc.
A "header file" in C++ is a file that mostly provides definitions, things that you might need to share between multiple ".cpp" files. A ".cpp" file is generally a "compilation unit", a discrete file that the compiler is expected to turn into a similarly named "object file".
So in what you've shown us your division of interest is wrong. You've actually implemented main in the ".h" file.
When the compiler reads your ".cpp" file, it reads in the iostream and string.h headers, and then it reads in a.h, which includes an implementation of main. Then, it returns to processing tryout.cpp where it sees another implementation of main.
Solution: Remove main from a.h.
You cannot have multiple main() functions. When compiling, the C++ complier will take the content of the header files and add them where your #include statement is. If it finds more than one main() function, it does not know where to set the start point for the executable. You will have to rename the header file function to something else. Also note that it is common practice not to include function definitions in header files, rather than to use function declarations and have the definitions in other .cpp or pre-compiled .lib files.
I have found this article to be helpful for learning about how headers work.
You cannot have two main functions. If you want to include your file you should put everything in a function or better build a class.

About getenv() on OSX

I need to get the value of the environment variable ANDROID_HOME on OSX (set in .bash_profile). I can verify its existence by typing echo $ANDROID_HOME in the terminal.
Here is the code: (Xcode project)
void testGetEnv(const string envName) {
char* pEnv;
pEnv = getenv(envName.c_str());
if (pEnv!=NULL) {
cout<< "The " << envName << " is: " << pEnv << endl;
} else {
cout<< "The " << envName << " is NOT set."<< endl;
}
}
int main() {
testGetEnv("ANDROID_HOME");
}
The output is always The ANDROID_HOME is NOT set.. I don't think I'm using getenv() correctly here. Either that, or .bash_profile is not in effect when the getenv() is called.
What am I missing?
Your code seems correct - so you're most probably calling your program in an environment where ANDROID_HOME is indeed not set. How are you starting your program?
I changed your source code to actually be compilable, and it works fine on my OS X system:
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
void testGetEnv(const string envName) {
char* pEnv;
pEnv = getenv(envName.c_str());
if (pEnv!=NULL) {
cout<< "The " << envName << " is: " << pEnv << endl;
} else {
cout<< "The " << envName << " is NOT set."<< endl;
}
}
int main() {
testGetEnv("ANDROID_HOME");
}
Compile that with:
g++ getenv.cpp -o getenv
Now run:
./getenv
The ANDROID_HOME is NOT set.
export ANDROID_HOME=something
./getenv
The ANDROID_HOME is: something

Errors when linking and compiling C++ files using TextPad/G++, possibly (probably) just syntax?

This very well could be a syntax error on my part since I am rather new with using multiple files and structs in C++ (in particular, passing structs to functions). Here are the three files:
main.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include "common.h"
using namespace std;
void honorStatus(int, student studentList[]);
int main(void)
{
int header;
string filename;
ifstream inputFile;
student studentList[MAX_STUDENTS];
// Get filename from user and try to open file
cout << "Please enter a filename: ";
cin >> filename;
inputFile.open(filename.c_str());
// If file cannot be opened, output error message and close program
if (inputFile.fail())
{
cout << "Input file could not be opened. Please try again." << endl;
return 1;
}
// Get header number from file. If header is larger than max number
// of students, error is output and program is closed
inputFile >> header;
if (header > MAX_STUDENTS)
{
cout << "Number of students has exceeded maximum of " << MAX_STUDENTS
<< ". Please try again." << endl;
return 1;
}
// Read file information (student ID, hours, and GPA) into struct array
for (int i = 0; i < header; i++)
{
inputFile >> studentList[i].ID >> studentList[i].hours >> studentList[i].GPA;
}
// Close the file
inputFile.close();
// Calls function honorStatus
honorStatus(header, studentList);
return 0;
}
functs.cpp:
#include <iostream>
#include "common.h"
using namespace std;
// Function to determine classification and honors society eligibility requirements
// of each student, outputting this information and the number of students eligible
void honorStatus(int fheader, student fstudentList[])
{
int cnt = 0;
for (int i = 0; i < fheader; i++)
{
if (fstudentList[i].hours < 30)
{
cout << "Student #" << fstudentList[i].ID << " is a freshman with GPA of "
<< fstudentList[i].GPA << ". Not eligible." << endl;
}
else if (fstudentList[i].hours > 29 && fstudentList[i].hours < 60)
{
if (fstudentList[i].GPA >= 3.75)
{
cout << "Student #" << fstudentList[i].ID << " is a sophomore with GPA of "
<< fstudentList[i].GPA << ". Eligible." << endl;
cnt++;
}
else
{
cout << "Student #" << fstudentList[i].ID << " is a sophomore with GPA of "
<< fstudentList[i].GPA << ". Not Eligible." << endl;
}
}
else if (fstudentList[i].hours > 59 && fstudentList[i].hours < 90)
{
if (fstudentList[i].GPA >= 3.5)
{
cout << "Student #" << fstudentList[i].ID << " is a junior with GPA of "
<< fstudentList[i].GPA << ". Eligible." << endl;
cnt++;
}
else
{
cout << "Student #" << fstudentList[i].ID << " is a junior with GPA of "
<< fstudentList[i].GPA << ". Not eligible." << endl;
}
}
else
{
if (fstudentList[i].GPA >= 3.25)
{
cout << "Student #" << fstudentList[i].ID << " is a senior with GPA of "
<< fstudentList[i].GPA << ". Eligible." << endl;
cnt++;
}
else
{
cout << "Student #" << fstudentList[i].ID << " is a senior with GPA of "
<< fstudentList[i].GPA << ". Not eligible." << endl;
}
}
}
cout << "\nTotal number of students eligible for the Honor Society is " << cnt << "." << endl;
}
common.h:
// Maximum number of students allowed
const int MAX_STUDENTS = 10;
// Struct for student info
struct student
{
int ID;
int hours;
float GPA;
};
When using TextPad/G++, I get the following error:
/cygdrive/c/Users/Korina/AppData/Local/Temp/ccxq9DAh.o:p7b.cpp:(.text+0x0): multiple definition of `main'
/cygdrive/c/Users/Korina/AppData/Local/Temp/ccmtzOP2.o:p5.cpp:(.text+0x0): first defined here
/cygdrive/c/Users/Korina/AppData/Local/Temp/ccLa96oD.o:test.cpp:(.text+0x0): multiple definition of `main'
/cygdrive/c/Users/Korina/AppData/Local/Temp/ccmtzOP2.o:p5.cpp:(.text+0x0): first defined here
/usr/lib/gcc/i686-pc-cygwin/4.8.2/../../../../i686-pc-cygwin/bin/ld: /cygdrive/c/Users/Korina/AppData/Local/Temp/ccmtzOP2.o: bad reloc address 0x1b in section `.text$_ZNSt11char_traitsIcE7compareEPKcS2_j[__ZNSt11char_traitsIcE7compareEPKcS2_j]'
collect2: error: ld returned 1 exit status
When using an online C++ compiler (CompileOnline), I get:
/tmp/ccIMwHEt.o: In function `main':
main.cpp:(.text+0x1cf): undefined reference to `honorStatus(int, student*)'
collect2: error: ld returned 1 exit status
I wasn't able to find a guide on how to set up TextPad/G++ to compile and link multiple files, but my instructor gave a short set of instructions that I followed. Here is how it's set up:
So this could a two-parter question (how do I set up TextPad to correctly compile/link files? why is my honorStatus() function undefined in main.cpp?) or it could just be that my syntax is wrong. I'm honestly not sure. Sorry if this is a bit long; I wanted to include as much detail as possible. Any help is greatly appreciated.
The problem is that you are compiling "*.cpp" all together. Given this
/cygdrive/c/Users/Korina/AppData/Local/Temp/ccxq9DAh.o:p7b.cpp:(.text+0x0): multiple definition of `main'
/cygdrive/c/Users/Korina/AppData/Local/Temp/ccmtzOP2.o:p5.cpp:(.text+0x0): first defined here
/cygdrive/c/Users/Korina/AppData/Local/Temp/ccLa96oD.o:test.cpp:(.text+0x0): multiple definition of `main'
/cygdrive/c/Users/Korina/AppData/Local/Temp/ccmtzOP2.o:p5.cpp:(.text+0x0): first defined here
/usr/lib/gcc/i686-pc-cygwin/4.8.2/../../../../i686-pc-cygwin/bin/ld: /cygdrive/c/Users/Korina/AppData/Local/Temp/ccmtzOP2.o: bad reloc address 0x1b in section `.text$_ZNSt11char_traitsIcE7compareEPKcS2_j[__ZNSt11char_traitsIcE7compareEPKcS2_j]'
collect2: error: ld returned 1 exit status
we can see that the the compiler has been trying to combine p5.cpp, p7b.cpp and test.cpp into one executable (possibly other .cpp files too).
You need to actually tell the compiler exactly which files you want to build together to one program. E.g.
g++ main.cpp functs.cpp -o main.exe
(I would suggest also adding -Wall -Wextra -Werror to the compile line, as that allows the compiler to detect the small mistakes that aren't strictly errors, but where you probably got something wrong)
From the linker output you can see that main function is found in these files: p7b.cpp, p5.cpp and test.cpp. As there's no main.cpp file listed in the linker output, I guess that current directory is setup to be where p7b.cpp and other files are located.
Try to change Initial Folder to be where your main.cpp file is set (something like /cygdrive/c/Users/Korina/programming/). Also, remove all unrelevant files from that directory, as you're compiling all cpp files.
The error message is clear enough. Your project contains the following files
p7b.cpp, p5.cpp, test.cpp
where in each file there is defined function main. Put a place in order with your project files.
As for the error message when you use the inline compiler then it seems module functs.cpp is not included in the project. So the compiler does not see the function definition.

How do I correct "expected primary-expression before...?"

I'm just beginning to program and I have no idea what I'm doing. My professor gave us Program Sets to do and I've completed it, but when I Compile the file I get
" J:\Untitled1.cpp In function `int main()':
"36 J:\Untitled1.cpp expected primary-expression before '<<' token "
Here's the full set, remember now that I'm a beginner:
/** CONCEPTS PROGRAM #1, TEMPLATE
PROGRAM Name: Yay.cpp
Program/assignment:
Description: Finds total
Input(s):
Output(s):
suffering_with_c++
Date of completion
*/
//included libraries
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <time.h.>
#define cls system("cls")
#define pauseOutput system("pause")//
using namespace std;
int main()
{
//variable declaration/initialization
time_t nowIsTheMoment;
time(&nowIsTheMoment);
string dateTime;//
cls;
cout <<"\new live in the moment--only this moment is ours. The Current Date and time is: "
<<ctime (&nowIsTheMoment); << endl;//
cout << "\nMy name is Moe Joe." <<endl;//
cout << endl << "I think Computer Programming with C++ will be a bit more PHUN now!"
<< endl;
dateTime = ctime(&nowIsTheMoment);//
cout << endl << "\nYo ho! I am here now...\n" << endl;
cout << endl << "The Current Date and time is: "
<<dateTime <<endl;//
cout << "\nI know clearly that, if I DO NOT comment my programs/project work thorougly, I will lose substantial points.\n" ;
cout << "\bHere is Pause Output in action....\n" << endl;//
pauseOutput; //
cls;//
return 0;
}
Remove the semicolon on line 36
<<ctime (&nowIsTheMoment); << endl;
^
|
You forgot to #include <string> and qualify string and cout with std::.
Start by removing the . after <time.h> it should probably help. Then you got this
ctime (&nowIsTheMoment); << endl;
which can't compile because << needs a left operand (ie: remove the semi-colon).
I don't mean to be rude, but you should try a little bit harder before asking questions on StackOverflow...