how do I compile a .c or .cpp file using GCC?
I need to include some standard libraries (fstream, string, iostream) - how do I do this?
For clarification, here:
#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include"ocgenerator.h";
#include"structures.h";
#include"util.h";
#include"util2.h";
using namespace std;
(my .h files are in the same directory as the src file)
If I use the command:
gcc src.cpp -o src.o
I get a lot of errors: memcpy, atoi, atol, strncmp, etc, ... "are not declared in this scope". What should I add to the command?
edit: Or is it a scope thing, and do I have to add std:: to all those functions?
memcpy and strncmp are declared in <cstring>, atoi and atol in <cstdlib>. Just include these headers to bring in their declarations.
Side notes :
No semicolon after preprocessor directives, including #include "".
No using namespace std;, especially not in headers !
(Why is "using namespace std" considered bad practice?)
Since you're building a C++ project, don't forget to link with the standard library via -lstdc++, or use g++ which forwards it to the linker for you.
Note that with GCC you don't have to prefix standard C functions with std:: (as they are also declared in the global namespace), but you should anyway for your code to be standard-compliant.
The cplusplus site helps out. If you search for a specific function, on the top you will find the necessary references for the code to compile:
http://www.cplusplus.com/reference/cstdlib/atol/
You can even check in the URL. In this case, you need 'cstdlib'.
Regarding the compiler, there are several available, g++ is a good option.
I also suggest creating a makefile for automating the building process, because it becomes an headache when your codebase grows.
For any library function you use in your code, read the man page for that function to see which header declares it, and #include that header in any source file that uses the function.
For example, man memcpy shows the memcpy(3) man page (the (3) refers to section 3 of the manual; use man 3 memcpy to specify the section).
NAME
memcpy - copy memory area
SYNOPSIS
#include <string.h>
void *memcpy(void *dest, const void *src, size_t n);
...
memcpy is part of the C standard library, and is declared in <string.h>. For C++ you can use <string.h>, but it's probably better to use <cstring>, which puts the function name in the std namespace. In general, each standard C header <foo.h> is duplicated as a C++ header <cfoo>.
I get a lot of errors: memcpy, atoi, atol, strncmp, etc,
memcpy and strncmp are declared in <cstring>. atoi and atol are <cstdlib> (or in <string.h> and <stdlib.h> if you're programming in C rather than in C++).
And be sure to use the g++ command, not the gcc command, to compile C++ source. They both invoke the same compiler (gcc compiles C++ code if the source file name ends in .cpp), but the g++ command adds some options that are needed for C++.
Related
I am trying to build my code using the Intel C++ Compiler, but for some reason it fails with this error:
catastrophic error: cannot open source file "stdio.h"
In this line #include <stdio.h>.
Any ideas?
stdio.h is a standard header file; it's a bad idea to have a local file of the same name. If you meant to include the standard header, it should be on your include path, and you should include it with
#include <stdio.h>
You should also consider whether you might get more benefit from including <iostream> or including <cstdio> (like including <stdio.h>, but puts the symbols safely into the std namespace).
If you're running on Windows, then installing Visual Studio, then invoking "psxevars.bat" might solve your problem, it solved it for me.
The following program compiles correctly:
#include <algorithm>
int main(int argc, char *argv[]) {
return int(log(23.f));
}
(under g++ 4.9.2 with the flag -std=c++11)
The code uses the function log, which is defined on <cmath>. However, it does not include the header <cmath>, only the header <algorithm>. Why is it that g++ doesn't give any warnings, and compiles the code correctly?
According to the standard, some headers do include others. As an example, <cinttypes> includes <cstdint>. See the Includes section here. With respect to <algorithm>, there is no such statement as to which other headers it should include (see here). So, the conclusion is, <algorithm> is not required to include <cmath>, and your example code is not portable. It may fail to compile on other C++ implementations.
In the C++11 standard, [res.on.headers]/1 states that
A C++ header may include other C++ headers. A C++ header shall provide
the declarations and definitions that appear in its synopsis. A C++
header shown in its synopsis as including other C++ headers shall
provide the declarations and definitions that appear in the synopses
of those other headers.
Now consider [algorithms.general]/2:
Header <algorithm> synopsis
#include <initializer_list>
namespace std {
// ......
<cmath> isn't listed and clearly not included in <initializer_list>. Thus your program is not guaranteed to compile on a standard-conforming implementation. One should never rely on "implicit inclusion" - the general guideline is to include every header from which an entity is used.
Exceptions are e.g. <iostream> including <ostream>, which is guaranteed since C++11.
To answer your question:
Why is it that g++ doesn't give any warnings, and compiles the code correctly?
Because C++ implementations aren't required to and it's actually quite difficult to implement this warning given the way #include works. Attempts have been made, but there are problems that haven't been entirely addressed.
Moving to a different model can enable this kind of checking. However, in the interests of backwards compatibility and allowing the easiest possible transition the 'modularizations' of the standard library I've used happen to explicitly allow code that previously depended on indirect includes to continue to work.
You can see this, for example, in libc++'s module map; Those export * lines declare "any modules imported by this module are also exported." Which is to say, a module std.algorithm that imports a module std.cmath also exports, so anyone that imports std.algorithm also gets access to std.cmath.
For new code it would be very nice if these 'legacy exports' could be turned off, but for pre-existing large projects it is very nice to be able to just flip on -fmodules and have the project work with no changes.
Using clang's implementation of modules with libc++, and modifying the module map file to remove the non-portable, indirect include behavior, clang reports such errors like:
main.cpp:5:16: error: declaration of 'log' must be imported from module 'Darwin.C.math' before it is required
return int(log(23.f));
^
/usr/include/math.h:387:15: note: previous declaration is here
extern double log(double);
^
1 error generated.
libc++ <algorithm> doesn't include <cmath>, so I used <random> instead. Otherwise the source that produced the above is the same as what you show.
I'm trying to make something in Linux, but it complains that it can't find iostream.h. What do I need to install to get this file?
The correct name of this standard header is just iostream without an extension.
If your compiler still cannot find it, try the following:
find /usr/include -name iostream -type f -print
...and add it to your include path, following your compiler's documentation.
The header <iostream.h> is an antiquated header from before C++ became standardized as ISO C++ 1998 (it is from the C++ Annotated Reference Manual). The standard C++ header is <iostream>. There are some minor differences between the two, with the biggest difference being that <iostream> puts the included contents in namespace std, so you have to qualify cin, cout, endl, istream, etc. with "std::". As somewhat of a hack (it is a hack because header files should never contain "using" directives as they completely defeat the purpose of namespaces), you could define "iostream.h" as follows:
#ifndef HEADER_IOSTREAM_H
#define HEADER_IOSTREAM_H
#include <iostream>
using namespace std; // Beware, this completely defeats the whole point of
// having namespaces and could lead to name clashes; on the
// other hand, code that still includes <iostream.h> was
// probably created before namespaces, anyway.
#endif
While this is not exactly identical to the original antiquated header, this should be close enough for most purposes (i.e. there should be either nothing or very few things that you will have to fix).
I needed to compile partport on Debian and had problems (CentOS 4.5 worked fine). I did this without any success:
ln -s /usr/include/c++/4.5/iostream /usr/include/c++/4.5/iostream.h
I discovered that iostream.h was provided from C++, and I found it on CentOS 4.5.
So I copied the file iostream.h from CentOS 4.5 to Ubuntu 11.04 (Natty Narwhal), and it worked:
scp root#ip.centos-4.5:/usr/include/c++/3.3.4/backward/iostream.h /usr/include/c++/4.5/iostream.h
I am compiling a large number of files which use srand() and rand() without including stdlib.h.
I'm aware that this is bad practice but, as I cannot change the files that I am compiling, inserting the necessary include statement in each file is not an option.
How can I configure my compiler to allow implicit inclusion of stdlib functions? Also, is there a way to implicitly use the std namespace in the same way?
Edit: Using g++
Edit: Looks like this is the answer (to the first part, at least). To compile a file as if stdlib.h is included, use the option -include stdlib.h
As you've now mentioned that you're using GCC, you can just use the -include flag. Other compilers probably have equivalents.
If you don't have such a flag for your compiler, you could use the following not-entirely-serious solution, that should work nevertheless:
nice.cc
#include <stdlib.h>
#include "naughty.cc"
(where naughty.cc is the original source file).
Of course, with a suitable build system, you could automatically generate the nice wrapper files.
Since you are already embracing bad practice, how about:
cat > foo.c << EOF
#include <stdlib.h>
#include "file-to-compile.c"
EOF
${CC} foo.c
You're using GCC, so you can use the -include option (from the manual):
Process file as if #include "file" appeared as the first line of the primary source file.
For example:
g++ -include stdlib.h foo.c
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.
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>).
The C language string is different than the C++ std::string.
The C language string type is a sequence of characters terminated by a nul, zero, '\0', character. The function declarations for managing this data structure are in <string.h> or <cstring>, depending on whether you compile as C or C++, respectively.
The C++ std::string type is a container of characters. The actual implementation may vary among compilers, but the interface won't. The methods of the std::string are declared in <string>. The compiler must be set up for compiling in the C++ language.
The C++ std::string has methods for generating C language strings and also for creating C++ strings from C language style strings. Read up on the Standard Template Library for more information.
Also, search the Web for "C++ FAQ". This is mandatory reading before programming in the C++ language. There is also a FAQ for the C language too.