2

I declared a function which returns std::string in read_qacct.h

#include <string>
std::string read_qacct(std::string login, int days);

Then I include read_qacct.h in another cpp file called db2class.cpp

#include "read_qacct.h"

When I compile db2class though, the first error is

In file included from db2class.cpp:8:
./read_qacct.h:2:6: error: redefinition of 'string' as different kind of symbol
std::string read_qacct(std::string login, int days);
     ^
/usr/include/c++/4.2.1/bits/stringfwd.h:59:33: note: previous definition is here
  typedef basic_string<char>    string;

I had read_qacct.h included the same way in read_qacct.cpp where the function read_qacct was defined. I successfully compiled read_qacct.cpp. How come I got this weird error for db2class.cpp?

ddd
  • 4,665
  • 14
  • 69
  • 125
  • 1
    It sounds like there's something wrong with the line before that declaration; perhaps a missing semi-colon so that `std::string` is treated as part of the previous line. – Mike Seymour Feb 27 '14 at 05:31

1 Answers1

0

You most likely forgot to guard one of your headers. Make sure to surround the headers by guards to prevent redefinitions:

#ifndef FILENAME_H
#define FILENAME_H

<content here>

#endif

These if statements get evaluated by the preprocessor. It basically ensures that the code between the guards is only processed when the file is first included, considering that FILENAME_H (where FILENAME can be anything unique, not necessarily the filename) is not yet defined ("ifndef", if not defined). However, on next includes, _FILENAME_H will already defined, causing the preprocessor to skip all the contents in the #if statement.

vijfhoek
  • 66
  • 1
  • 7
  • I don't see how this fixes the problem based on what's shown in the question. – chris Feb 27 '14 at 05:41
  • I can't know, @user3358927 did not post any examples so I just guessed whatever made most sense. – vijfhoek Feb 27 '14 at 13:04
  • This seems to have fixed it. Do I need the guards in every header file? What does it do really? – ddd Feb 27 '14 at 15:35
  • @user3358927 As I explained under the code, it prevents the compiler from including the file twice, defining everything multiple times. Unlike modern languages, #include just flat out smacks everything from the included file into the file it's in. And yes, you need it in every header file. Modern compilers also support "#pragma once" instead of the whole #ifndef...#define...#endif business, but there are some catches to that. – vijfhoek Feb 27 '14 at 16:12