Compile errors with linked files in C++ - c++

Edit: I've reduced a majority of the errors with the std:: prefix on string declarations. However, there seems to be a problem with a few functions, particularly the definitions of those functions who have a string as a parameter.
Edit #2: Updated my code (I DID have the std:: prefix on my function declarations, but hadn't reflected it in my post). Please see the very bottom for errors displayed when I add the std:: prefix to string parameters in the problematic functions.
I have a header file movie.h with the following code (relevant code):
#include <string>
class Movie
{
public:
void addMovieName(std::string movie);
void addLastName(std::string nameLast);
void addFirstName(std::string nameFirst);
private:
string movieName,
directorLastName,
directorFirstName,
directorFullName;
};
And an implementation file movie.cpp like this (relevant code):
#include "movie.h"
// addFirstName, addLastName, and addMovie name all do the same things
// so I'm only including one since they all generate the same error
void Movie::addFirstName(string nameFirst)
{
directorFirstName = nameFirst.resize(10, ' ');
}
Upon compilation, I get the following errors:
g++ -c movie.cpp -o movie.o
movie.cpp:225: error: variable or field ‘addFirstName’ declared void
movie.cpp:225: error: ‘int Movie::addFirstName’ is not a static member of ‘class Movie’
movie.cpp:225: error: ‘string’ was not declared in this scope
movie.cpp:226: error: expected ‘,’ or ‘;’ before ‘{’ token
movie.cpp:240: error: variable or field ‘addLastName’ declared void
movie.cpp:240: error: ‘int Movie::addLastName’ is not a static member of ‘class Movie’
movie.cpp:240: error: ‘string’ was not declared in this scope
movie.cpp:241: error: expected ‘,’ or ‘;’ before ‘{’ token
movie.cpp:255: error: variable or field ‘addMovieName’ declared void
movie.cpp:255: error: ‘int Movie::addMovieName’ is not a static member of ‘class Movie’
movie.cpp:255: error: ‘string’ was not declared in this scope
movie.cpp:256: error: expected ‘,’ or ‘;’ before ‘{’ token
make: *** [movie.o] Error 1
Some of who have said I need to prepend std:: to the string parameters in the function definitions.
Upon doing this:
// adding std:: prefix
void Movie::addFirstName(std::string nameFirst)
{
directorFirstName = nameFirst.resize(10, ' ');
}
I get the following errors. Note that I only changed it for a single function. The first errors I don't understand, whereas the rest remain the same as before.
g++ -c movie.cpp -o movie.o
movie.cpp: In member function ‘void Movie::addFirstName(std::string)’:
movie.cpp:227: error: no match for ‘operator=’ in ‘((Movie*)this)->Movie::directorFirstName = nameFirst.std::basic_string<_CharT, _Traits, _Alloc>::resize [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>](10u, 32)’
/usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h:485: note: candidates are: std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h:493: note: std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(const _CharT*) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h:504: note: std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(_CharT) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
movie.cpp: At global scope:
movie.cpp:240: error: variable or field ‘addLastName’ declared void
movie.cpp:240: error: ‘int Movie::addLastName’ is not a static member of ‘class Movie’
movie.cpp:240: error: ‘string’ was not declared in this scope
movie.cpp:241: error: expected ‘,’ or ‘;’ before ‘{’ token
movie.cpp:255: error: variable or field ‘addMovieName’ declared void
movie.cpp:255: error: ‘int Movie::addMovieName’ is not a static member of ‘class Movie’
movie.cpp:255: error: ‘string’ was not declared in this scope
movie.cpp:256: error: expected ‘,’ or ‘;’ before ‘{’ token
make: *** [movie.o] Error 1

You have not specified the correct namespace for string, string is a member of the std namespace. In this case you need to write std::string since I see no "using namespace std;" in your code.
replace:
string movieName,
directorLastName,
directorFirstName,
directorFullName;
with:
std::string movieName,
directorLastName,
directorFirstName,
directorFullName;

Why are all your private fields pointers? Storing plain ints and floats as fields is perfectly okay. Moreover, you don't need to "initialize" strings in your constructor. If you don't, their default constructors will be called automatically (strings will be empty). And why do you pad strings? Even if you need it when displaying, pad them there.

No one has answered the question yet, so I figured I'd just put it here myself since I figured it out. Basically, my solution was:
Use using std::string in header and implementation files.
Secondly, the declaration:
stringOne = stringTwo.resize(some_number, ' ');
...fails because resize() is a void returning function. Replacing that with two separate statements; namely:
stringOne = stringTwo;
stringOne.resize(/* blah */);
...solves the rest of the errors. Credit to #Jesse for mentioning this in the comments.

Related

No narrowing warnings when using `emplace_back` instead of `push_back`

My colleague ran into an unexpected issue with emplace_back and I am trying to wrap my head around it. The following test.cpp is a minimal example that reproduces the issue:
#include <vector>
class A {
public:
explicit A(int /*unused*/) {}
};
int main() {
double foo = 4.5;
std::vector<A> a_vec{};
a_vec.emplace_back(foo); // No warning with Wconversion
A a(foo); // Gives compiler warning with Wconversion as expected
}
Compiling with g++ 8.3.0 yields the following warning:
$ g++ -Wconversion test.cpp -o test
test.cpp: In function ‘int main()’:
test.cpp:10:10: warning: conversion from ‘double’ to ‘int’ may change value [-Wfloat-conversion]
A a(bar); // Gives compiler warning with Wconversion as expected
So the implicit conversion is caught when a simple object is constructed, but not when emplace_back is called.
Why is there no warning for emplace_back?
This is a consequence of how the default allocator constructs an A. When you do A a{foo, bar} you are using list initialization and a narrowing conversion is required to issue a diagnostic. With the default allocator, it uses
::new (static_cast<void*>(p)) T(std::forward<Args>(args)...)
where p is a pointer to the element of the vector data and T is the value_type of the vector. Here they use parentheses instead of braces and with parentheses narrowing conversions are allowed so you don't see a diagnostic message.
If you wrote your own allocator that did
::new (static_cast<void*>(p)) T{std::forward<Args>(args)...}
Then you would get the warning.
In order to get the warning you need to compile with:
$ g++ -Wsystem-headers -Wconversion test.cpp -o test
In file included from /usr/include/c++/8/vector:60,
from test.cpp:1:
/usr/include/c++/8/bits/stl_algobase.h: In function ‘constexpr int std::__lg(int)’:
/usr/include/c++/8/bits/stl_algobase.h:1001:44: warning: conversion from ‘long unsigned int’ to ‘int’ may change value [-Wconversion]
{ return sizeof(int) * __CHAR_BIT__ - 1 - __builtin_clz(__n); }
^
/usr/include/c++/8/bits/stl_algobase.h: In function ‘constexpr unsigned int std::__lg(unsigned int)’:
/usr/include/c++/8/bits/stl_algobase.h:1005:44: warning: conversion from ‘long unsigned int’ to ‘unsigned int’ may change value [-Wconversion]
{ return sizeof(int) * __CHAR_BIT__ - 1 - __builtin_clz(__n); }
^
In file included from /usr/include/x86_64-linux-gnu/c++/8/bits/c++allocator.h:33,
from /usr/include/c++/8/bits/allocator.h:46,
from /usr/include/c++/8/vector:61,
from test.cpp:1:
/usr/include/c++/8/ext/new_allocator.h: In instantiation of ‘void __gnu_cxx::new_allocator<_Tp>::construct(_Up*, _Args&& ...) [with _Up = A; _Args = {double&}; _Tp = A]’:
/usr/include/c++/8/bits/alloc_traits.h:475:4: required from ‘static void std::allocator_traits<std::allocator<_Tp1> >::construct(std::allocator_traits<std::allocator<_Tp1> >::allocator_type&, _Up*, _Args&& ...) [with _Up = A; _Args = {double&}; _Tp = A; std::allocator_traits<std::allocator<_Tp1> >::allocator_type = std::allocator<A>]’
/usr/include/c++/8/bits/vector.tcc:103:30: required from ‘void std::vector<_Tp, _Alloc>::emplace_back(_Args&& ...) [with _Args = {double&}; _Tp = A; _Alloc = std::allocator<A>]’
test.cpp:9:25: required from here
/usr/include/c++/8/ext/new_allocator.h:136:4: warning: conversion from ‘double’ to ‘int’ may change value [-Wfloat-conversion]
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
The warning is no longer as clear, since it happens in a system header. Note that it is not enough to only use the -Wsystem-headers flag, one needs both -Wsystem-headers and -Wconversion to catch this.
In the case of push_back it is enough to use -Wnarrowing to get a warning.

C++ writing to file error in Linux/Ubuntu?

I have been trying to learn C++ recently, but I have stumbled across some errors. For example, when I try to run this code to ask the user what they want outputted to a file:
#include <iostream>
#include <cstdio>
using namespace std;
main() {
string output; //Declare variables before starting
FILE * file = fopen("newfile.txt","w"); //creates file
cout << "Entire something that you want to be written to the file: " << endl;
cin.getline(output, 256); //Asks what you want to put into file
fprintf(file, output); //Puts output into file
fclose(file); //closes file
return 0;
}
using
g++ -o main test.cpp
I get this error:
test.cpp: In function ‘int main()’:
test.cpp:10:25: error: no matching function for call to ‘std::basic_istream<char>::getline(std::string&, int)’
cin.getline(output, 256);
^
test.cpp:10:25: note: candidates are:
In file included from /usr/include/c++/4.8/iostream:40:0,
from test.cpp:1:
/usr/include/c++/4.8/istream:618:5: note: std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::getline(std::basic_istream<_CharT, _Traits>::char_type*, std::streamsize, std::basic_istream<_CharT, _Traits>::char_type) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::char_type = char; std::streamsize = long int]
basic_istream<char>::
^
/usr/include/c++/4.8/istream:618:5: note: candidate expects 3 arguments, 2 provided
/usr/include/c++/4.8/istream:427:7: note: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::getline(std::basic_istream<_CharT, _Traits>::char_type*, std::streamsize) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>; std::basic_istream<_CharT, _Traits>::char_type = char; std::streamsize = long int]
getline(char_type* __s, streamsize __n)
^
/usr/include/c++/4.8/istream:427:7: note: no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘std::basic_istream<char>::char_type* {aka char*}’
test.cpp:11:22: error: cannot convert ‘std::string {aka std::basic_string<char>}’ to ‘const char*’ for argument ‘2’ to ‘int fprintf(FILE*, const char*, ...)’
fprintf(file, output);
^
Could someone please help me? And please forgive me if this is something that can be easily solved, I am fairly new to C++ and do not quite understand it yet.
The header for string is missing:
#include <string>
Without it, sring isn't defined, and everywhere you use output, you'll have errors
With the include you'll have a lot less errors. But this line has another issue (as πάντα ῥεῖ already pointed out):
cin.getline(output, 256);
because cin.getline() expects a char* and the length. If you want to use a string, you have to use the function getline(), without size (limited to strings maximume size) and on an istream:
getline(cin, output);
Last remark: you are of course free to mix c-style io and streams. But you could win from getting used to streams for all your file io.
The error occurs at the line
cin.getline(output, 256);
According to the documentation for std::istream::getline, the first argument for cin.getline() should be a char * and not a std::string as you have declared it.
Try changing the declaration of output to a char * like so
char[256] output;
Edit: Using std::getline as the others have said would be a better idea though.

Compile header file and two .cpp files in Unix/Linux (Ubuntu)

I am trying to compile 3 files total and can not get it to. The code works in visual++. I have uploaded all 3 files in the same dir and used the following command.
g++ -o edit Album.cpp lab8.cpp
My file names are listed below
Album.cpp
Album.h
lab8.cpp
Note the code was written in visual studio C++ and compiled just fine there.
Results in the following
lab8.cpp: In function ‘std::vector read_album_file(std::string)’:
lab8.cpp:142:25: error: no matching function for call to ‘std::basic_ifstream::basic_ifstream(std::string&)’
ifstream read (filename);// the ifstream is used to read from the file
^
lab8.cpp:142:25: note: candidates are:
In file included from lab8.cpp:38:0:
/usr/include/c++/4.8/fstream:467:7: note: std::basic_ifstream<_CharT, _Traits>::basic_ifstream(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits; std::ios_base::openmode = std::_Ios_Openmode]
basic_ifstream(const char* __s, ios_base::openmode __mode = ios_base::in)
^
/usr/include/c++/4.8/fstream:467:7: note: no known conversion for argument 1 from ‘std::string {aka std::basic_string}’ to ‘const char*’
/usr/include/c++/4.8/fstream:453:7: note: std::basic_ifstream<_CharT, _Traits>::basic_ifstream() [with _CharT = char; _Traits = std::char_traits]
basic_ifstream() : __istream_type(), _M_filebuf()
^
/usr/include/c++/4.8/fstream:453:7: note: candidate expects 0 arguments, 1 provided
/usr/include/c++/4.8/fstream:427:11: note: std::basic_ifstream::basic_ifstream(const std::basic_ifstream&)
class basic_ifstream : public basic_istream<_CharT, _Traits>
^
/usr/include/c++/4.8/fstream:427:11: note: no known conversion for argument 1 from ‘std::string {aka std::basic_string}’ to ‘const std::basic_ifstream&’
Look at the constructor prototype of ifstream. It takes a const char * and a optional argument, soyou need to write filename.c_str()

map in c++ causes error

I have header file. I want a map object added to one of the structures. So I included
#include<map>
and compiled the program (note I did not use map object I just included it) and I got the following error
/usr/include/c++/4.7/bits/stl_map.h:115:28: error: macro "value_compare" requires 2 arguments, but only 1 given
/usr/include/c++/4.7/bits/stl_map.h:733:45: error: macro "value_compare" requires 2 arguments, but only 1 given
In file included from /usr/include/c++/4.7/map:62:0,
from ../optimizer_types.h:16,
from ../main.cpp:20:
/usr/include/c++/4.7/bits/stl_multimap.h:115:28: error: macro "value_compare" requires 2 arguments, but only 1 given
/usr/include/c++/4.7/bits/stl_multimap.h:656:45: error: macro "value_compare" requires 2 arguments, but only 1 given
In file included from /usr/include/c++/4.7/map:61:0,
from ../optimizer_types.h:16,
from ../main.cpp:20:
/usr/include/c++/4.7/bits/stl_map.h:113:11: error: invalid use of non-static data member 'std::map<_Key, _Tp, _Compare, _Alloc>::value_compare::comp'
/usr/include/c++/4.7/bits/stl_map.h:116:4: error: from this location
/usr/include/c++/4.7/bits/stl_map.h:116:9: error: '__c' was not declared in this scope
/usr/include/c++/4.7/bits/stl_map.h:116:12: error: a function call cannot appear in a constant-expression
/usr/include/c++/4.7/bits/stl_map.h:116:12: error: expected ';' at end of member declaration
/usr/include/c++/4.7/bits/stl_map.h:116:14: error: expected unqualified-id before '{' token
/usr/include/c++/4.7/bits/stl_map.h: In member function 'std::map<_Key, _Tp, _Compare, _Alloc>::value_compare std::map<_Key, _Tp, _Compare, _Alloc>::value_comp() const':
/usr/include/c++/4.7/bits/stl_map.h:733:46: error: expected primary-expression before ';' token
In file included from /usr/include/c++/4.7/map:62:0,
from ../optimizer_types.h:16,
from ../main.cpp:20:
/usr/include/c++/4.7/bits/stl_multimap.h: At global scope:
/usr/include/c++/4.7/bits/stl_multimap.h:113:11: error: invalid use of non-static data member 'std::multimap<_Key, _Tp, _Compare, _Alloc>::value_compare::comp'
/usr/include/c++/4.7/bits/stl_multimap.h:116:4: error: from this location
/usr/include/c++/4.7/bits/stl_multimap.h:116:9: error: '__c' was not declared in this scope
/usr/include/c++/4.7/bits/stl_multimap.h:116:12: error: a function call cannot appear in a constant-expression
/usr/include/c++/4.7/bits/stl_multimap.h:116:12: error: expected ';' at end of member declaration
/usr/include/c++/4.7/bits/stl_multimap.h:116:14: error: expected unqualified-id before '{' token
/usr/include/c++/4.7/bits/stl_multimap.h: In member function 'std::multimap<_Key, _Tp, _Compare, _Alloc>::value_compare std::multimap<_Key, _Tp, _Compare, _Alloc>::value_comp() const':
/usr/include/c++/4.7/bits/stl_multimap.h:656:46: error: expected primary-expression before ';' token
As an experiment I moved the include to a cpp file and it was compiling properly.
What could be the reason
Try this:
#ifdef value_compare
#undefine value_compare // std::map header doesn't like this
#endif
#include <map>
It's not very flexible (or pretty) but it should get you through this :(
Edit: Either way, the problem is not including map, but the earlier include/code that defined value_compare macro. Is it a C header? (I doubt a C++ would define a macro with this name, as value_compare is an important part of the C++ standard library).

Boost date_time cpp files missing

I'm trying to compile this program and I'm having trouble finding the following files online:
#include <libs/date_time/src/posix_time/posix_time_types.cpp>
#include <libs/date_time/src/gregorian/date_generators.cpp>
speed_test\speed_test.cpp|42|error: boost/date_time/posix_time/posix_time_types.cpp: No such file or directory|
speed_test\speed_test.cpp|43|error: boost/date_time/gregorian/date_generators.cpp: No such file or directory|
speed_test\MruCache.h||In member function 'void MruCache<key_type, value_type>::__insert_item(key_type, value_type)':|
speed_test\MruCache.h|70|error: 'ptrItr' was not declared in this scope|
speed_test\MruCache.h|71|error: expected primary-expression before ')' token|
speed_test\MruCache.h|71|error: expected ';' before 'mapOfListIteratorPtr'|
speed_test\MruCache.h|87|error: expected type-specifier|
speed_test\MruCache.h|87|error: expected ';'|
speed_test\MruCache.h||In member function 'value_type MruCache<key_type, value_type>::__find_item(key_type)':|
speed_test\MruCache.h|104|error: 'ptrItr' was not declared in this scope|
speed_test\MruCache.h|105|error: expected primary-expression before ')' token|
speed_test\MruCache.h|105|error: expected ';' before 'mapOfListIteratorPtr'|
C:\Dev-Cpp\project2\speed_test\MruCache.h||In member function 'virtual void MruCache<key_type, value_type>::__clear()':|
speed_test\MruCache.h|119|error: expected ';' before 'i'|
speed_test\MruCache.h|120|error: 'i' was not declared in this scope|
speed_test\MruCache.h|123|error: 'pItr' was not declared in this scope|
speed_test\MruCache.h|123|error: expected primary-expression before ')' token|
speed_test\MruCache.h|123|error: expected ';' before 'ptrItr'|
speed_test\mru.h|142|error: type/value mismatch at argument 1 in template parameter list for 'template<class _T1, class _T2> struct std::pair'|
speed_test\mru.h|142|error: expected a type, got 'boost::unordered_map::iterator'|
speed_test\mru.h|143|error: invalid type in declaration before '=' token|
speed_test\speed_test.cpp||In function 'int main(int, char**)':|
speed_test\speed_test.cpp|178|error: 'ihash' was not declared in this scope|
speed_test\speed_test.cpp|178|error: template argument 3 is invalid|
speed_test\speed_test.cpp|178|error: invalid type in declaration before ';' token|
speed_test\speed_test.cpp|186|error: request for member 'clear' in 'tiles1_2', which is of non-class type 'int'|
speed_test\speed_test.cpp|191|error: no match for 'operator[]' in 'tiles1_2[keys.std::vector<T, Allocator>::operator[] [with _Tp = tile_id, _Alloc = std::allocator<tile_id>](((unsigned int)i))]'|
speed_test\speed_test.cpp|202|error: no match for 'operator[]' in 'tiles1_2[keys.std::vector<T, Allocator>::operator[] [with _Tp = tile_id, _Alloc = std::allocator<tile_id>](((unsigned int)i))]'|
speed_test\speed_test.cpp|433|error: request for member 'find' in 'tiles1_2', which is of non-class type 'int'|
speed_test\speed_test.cpp|560|error: request for member 'clear' in 'tiles1_2', which is of non-class type 'int'|
speed_test\mru.h|241|instantiated from 'Value& mru::list<Key, Value>::operator[](const Key&) [with Key = tile_id, Value = boost::shared_ptr<test>]'|
speed_test\speed_test.cpp|340|instantiated from here|
speed_test\mru.h|143|error: dependent-name 'boost::unordered_map::value_type' is parsed as a non-type, but instantiation yields a type|
speed_test\mru.h|143|note: say 'typename boost::unordered_map::value_type' if a type is meant|
speed_test\mru.h|241|instantiated from 'Value& mru::list<Key, Value>::operator[](const Key&) [with Key = tile_id, Value = boost::shared_ptr<test>]'|
speed_test\speed_test.cpp|340|instantiated from here|
speed_test\mru.h|143|warning: unused variable 'p'|
||=== Build finished: 27 errors, 1 warnings ===|
You seem to have some mistake in the #include directive, boost libraries are usually included as
#include <boost/whatever.hpp>
or
#include <boost/module/header.hpp>
Or if the boost libraries were not installed to your include paths and it is present in the current directory:
#include "boost_1_46_1/boost/..."
Rules for the filename are as said above
Read the docs for more info