Search code examples
c++powerpc

string.h and <string>


I am trying to build a library in a legacy C++ project. Platform is power-pc using gcc compiler.

The compiler is giving build errors similar to this: error: string: No such file or directory or error: vector: No such file or directory.

  • My understanding is that it is not able to locate the standard library. Where are the standard library files typically reside, and in what format? Is it *.h or some other? I searched for this on internet but I don't think I fully understand it.

  • The confusing part is that another library in the same project using same source code file builds prefectly alright. This suggests to me that may be the makefiles for these two projects are different, where one IS able to locate the std lib, other isn't. But a quick comparison b/w the two didn't bring up any obvious differences. Any other thoughts on this please?

  • Lastly, I just learned that string.h is for c-style strings, and string is for C++ std lib. Is it ok to mix them, i.e. a source file has #include string.h, and also #include string implicitly through including some other file? I ask because this is the same situation in the file that is not building.

Thanks.

Error Message:

Compiling SOURCE_FILE.cpp

In file included from SOURCE_FILE.cpp:3:

HDR_FILE.h:1: error: string: No such file or directory

HDR_FILE.h:2: error: vector: No such file or directory

CODE IN SOURCE_FILE.cpp

#include <stdlib.h>
#include <string.h>
#include "fileABC.h"

using namespace std;

// Other code

CODE IN HRD_FILE.h

#include <string>
#include <vector>
#include <hdr.h>
#include <hdr-cseq.h>
//... OTHER FILES ETC.

Solution

  • If the files are not being detected as C++ source code then you can get errors like this. Are the c++ files named using an appropriate file extension?

    cat test.c

    #include <vector>
    int main() {}
    

    gcc test.c

    test.c:1:18: error: vector: No such file or directory
    

    The command above will compile C code, but not C++. Remember that these are two different languages. To build C++ programs you have to tell the compiler that the source is C++ one way or another. If you use g++ it will automatically assume files with '.c' extensions are C++ (at least my version does. Or you can tell the compiler to use C++ by passing -x c++ right before you pass the file. You also have to tell the linker to include the C++ library. g++ does this automatically as well, or you can pass the linker flag -lstdc++.

    The hard way:

    gcc -x c++ test.c -lstdc++

    The easy way:

    g++ test.c

    In answer to your last question, you can freely mix <string.h> and <string> (though you should probably use <cstring> instead of <string.h>).