I created my own string class and named it 'String.hpp' and included this file in my 'String.cpp'. However, g++/gcc says it could not find 'String.hpp' no matter what I tried. Furthermore, it also cannot find the class named 'String'.
I thought strings in c++ were lowercase 'string'. Is 'String' a reserved class or word in C++?
EDIT:
I seemed to have solved this issue by redoing the code body. The names have all remained the same. I guess the next time this happens, I will look through my own code and try to find a problem there.
In C++ a string is a standard defined type not a keyword. And is use like so
#include <string>
//elsewhere
std::string str("hi");
If your compiler can't find your string header then it ins't going to know about your class whatever happens.
You should include your own header like this. Note the quotations, not the angle braces. Angle braces mean that the compiler should search the include directories not the current directory.
#include "String.hpp"
//else where
yournamepsace::String str //etc...
This won't collide with the standard version, you should however make sure that it is namespaced as you will be no doubt dealing with very similar names.
If the compiler still can't see then you need to make sure that the file is in the same directory that your source file is in.
Finally if this is some sort of programming practice then carry on but if this is production code please consider using the std::string, the world doesn't need another string. :)
My suspicion is you are doing a
#include <String.hpp>
This excludes the current directory from the where the compiler will search for the file. If that is the case, you want to do
#include "String.hpp"
in which case, the compiler will also search the current directory.
Related
I'm trying to use (Ligra) in a project. The framework works as long as the chief header "ligra.h" is included. Trouble is, that header has an implementation of parallel_main, which is a macro wrapper around main with OpenMP trickery. So if I wanted to write a simple program:
#include "ligra.h"
#include <iostream>
int main(){
std::cout<<"Hello World";
return 0;
}
It would not compile. Redefinition of symbol main.
Also, I need a parallel_main, with the exact macro trickery done in the "parallel.h" header.
So I think I have two options:
1) modify the file, add a pair of #ifdef LIGRA_MAIN's and not define the macro at compile time. Thus I can have my own main and not have redefinition. Trouble is I need my project to be using the upstream version of ligra, and Julian Shun, the original developer has probably forgottten about his project (and github, since he ignored more than one pull request).
2) Use/Write a #pragma that would strip that function out at the include stage.
I don't know how to do that last part, and would be very much in your debt if someone who did, reached out.
A solution that does not involve modifying library files (but is somewhat brittle) could be to do the following:
#include "ligra/parallel.h" (this does #define parallel_main main).
#undef parallel_main to prevent this rewriting of function names.
#include "ligra/ligra.h" as usual. Since parallel.h has an include guard, its repeated inclusion is prevented and parallel_main will not be redefined.
Proceed as normal.
You might also want to wrap this into a header so you only have to write it once.
Alternatively, you could do what #user463035818 suggests and redefine main only for the inclusion of ligra.h for very similar effect. The difference is in the names that the parallel_main function(s) from ligra will get.
You can simply not include ligra.h. If there is something useful in that file, then create a copy of the file - excluding the main function - and use that copy.
Sure, that means that if the upstream ligra.h is updated, your copy will not have the corresponding changes. However, given the premise "the original developer has probably forgottten about his project", this is probably not a problem. If the premise is wrong, then a better approach would be to create a pull request to make the framework usable as a library.
I'm building a little language that will compile to C or C++, I haven't decided yet, however I have come across a dilemma concerning the #include keyword.
My language will come with a standard library that will be incorporated into the language, and be accessible much like that of C or C++ with the standard includes such as #include <string>.
My compiler can automatically tell the difference between user includes and standard library includes, but my issue lies in how the GCC compiler uses the -I flag.
Let's take Java as an example. One of the default packages (folder) is called java.util. If I try to make my own folder called java.util inside my project, I get the error:
The package java.util conflicts with a package accessible from another module: java.base
Meaning it is included by default.
I would like this to do the same thing in C++, but am worried that a user could (hypothetically) do a relative path include and cause a conflict.
Take for example, I use the flag like so: -I ../some/folder.
However then the user could simply type #include "../some/folder" to access the same content. Is there any way I can restrict this, and like the title of the question suggests, "protect" the folder from being called like that?
Furthermore, if there is a file inside of that folder called test.h and the user decides to create their own file called test.h locally and include it. How will the conflicts occur? Will it pick the local folder over the included via. flags?
An example of a basic implementation is as follows: (General syntax, no specific language)
boolean userDefine = false;
string defineName = "foo";
// Do something to determine if <> define or "" define.
if (userDefine) {
// Returns #include "foo"
return "#include \"" + defineName + "\"";
} else {
// Returns #include "stdlib/foo"
return "#include \"stdlib/" + defineName + "\"";
}
But then again, the user could include the folder so that it satisfies the first condition and still gain access.
It's pretty much the standard practice to put any #include files at the very beginning of the C++ source file, as the first order of business.
Of course, a #include can appear anywhere in the C++ source file, and there are situations when that happens but, if you were to grab some random C++ source from github, chances are pretty good that all the #include files will be at the beginning of the file.
So, all you have to do, is to make arrangements that your library's #include is always at the beginning, and use the standard #ifndef/#define guards in your header files. Then, manual inclusion of them subsequently will have no effect whatsoever, no matter what path is used.
Of course, this won't stop anyone from manually #undefing your guard, to create some chaos. However, C++ never had a reputation for reliably preventing you from shooting yourself in the foot, and is unlikely to earn that reputation in the foreseeable future; so what? Actually, most compilers implement #pragma once, which might be a slightly better foot self-shooting prevention approach...
Our C++ library contains a file with a namethat is (considered) equal to one of the standard libraries' headers. In our case this is "String.h", which Windows considers to be the same as "string.h", but for the sake of this question it could be any other ile name used in the standard library.
Normally, this file name ambiguity is not a problem since a user is supposed to set up the include paths to only include the parent of the library folder (therefore requiring to include "LibraryFolder/String.h") and not the folder containing the header.
However, sometimes users get this wrong and directly set the include path to the containing folder. This means that "String.h" will be included in place of "string.h" in both the user code and in the standard library headers, resulting in a lot of compile errors that may not be easy to resolve or understand for beginners.
Is it possible, during compile-time, to detect such wrongly set up include paths in our libraries' header and throw a compile #warning or #error right away via directive, based on some sort of check on how the inclusion path was?
There's no failsafe way. If the compiler finds another file, it won't complain.
However, you could make it so you can detect it. In your own LibraryName/string.h, you could define a unique symbol, like
#define MY_STRING_H412a55af_7643_4bd6_be5c_4315d3a1e6b7
Then later in dependent code you could check
#ifndef MY_STRING_H412a55af_7643_4bd6_be5c_4315d3a1e6b7
#error "Custom standard library path not configured correctly"
#endif
Likewise you could use this to detect when the wrong version of the library was included.
[edit - as per comments]
Header inclusion can be summarized as :
Parse #include line to determine header name to look up
Depending on <Foo.h> or "Foo.h" form, determine set of locations (usually directories) to search
Interpret the header name, in an implementation-dependent way. (usually as a relative path). Note that this is not necessarily as a string, e.g. MSVC doesn't treat \ as a string escape character.
If the header is found (usually, if a file is found), replace the #include line with the content of that file. If not, fail the compilation.
(The parenthesized "usually" apply to MSVC, GCC, clang, etc but theoretically a compiler could compile directly from a git repository instead of disk files)
The problem here is that the test imagined (spelling of header name) must be located in the included header file. This test would necessarily be part of the replaced #include line, which therefore no longer exists and cannot be tested.
C++17 introduces __has_include but this does not affect the analysis: It would still have to occur in the included header file, and would not have the character sequence from the #include "Foo.h" available.
[old]
Probably the easiest way, especially for beginners is to have a LibraryName/LibraryName.h. Hopefully that name is unique.
The benefit is that once that works, users can replace #include "LibraryName.h" with just #include "String.h" as you know the path is right.
That said, "String.h" is asking for problems. Windows isn't case sensitive.
Use namespaces. In your case this would translate into something like this:
MyString/String.h
namespace my_namespace {
class string {
...
}
}
Now to make sure your std::string or any other class named string is not accidentally used instead of my_namespace::string (by any means, including but not limited to setting up your include paths incorrectly) you need to refer to your type using its fully qualified name, namely my_namespace::string. By doing this you avoid any naming clashes and are guaranteed to get a compile error if you don't include the correct header file (unless there's actually exists another class called my_namespace::string that is not yours). There are other ways to avoid these clashes (such as using my_namespace::string) but I'd rather be explicit about the types I'm using. This solution is costly however because it probably needs change all over your code base (changing all strings to my_namespace::string).
A somewhat less cumbersome alternative would be to change the name of the header String.h to something like MyString.h. This would quickly introduce compile errors but requires changing all your includes from #include "String.h" into#include "MyString.h"` (Should be much less effort compared to the first option).
I cannot think of any other way that requires less effort as of now. Since you were looking for a solution that would work in all similar scenarios I'd go with the namespaces if I were you and solve the problem once and for all. This would prevent any other existing/future naming clashes that may be in you code.
I have a templated class KeyValue, which defines a key-value pair.
The class KeyValue resides in ::distributed::utils namespace;
Now if I want to use KeyValue, I could either write ::distributed::utils::KeyValue my_kv;
Or for convenience, I could import the namespace:
using ::distributed::utils::KeyValue;
and then just type KeyValue my_kv, whenever I need to use this class.
The problem now I have is that using ::distributed::utils::KeyValue in a header file
violates the company I work for styleguide (so no "using" allowed in a header file).
Also, I'm writing some templated functions in a header file, and so I can't move them to cc file (any nasty way to do that would also be considered as style-guide violation).
Therefore, the question is:
What would be the good way around it?
One possibility I found is to abbreviate ::distributed::utils namespace by
namespace ::distributed::utils du;
And then write du::KeyValue wherever I need KeyValue object.
But that's still not excellent, as I would need to change KeyValue to distributed::utils::KeyValue many times (and some other classes as well).
So, any help of how to abbreviate ::distributed::utils::KeyValue by KeyValue inside a header file?
Thanks a lot in advance.
P.s. Changed names to something else not to show companys code.
I suggest not to seek the answer in the code. As it is often stated, code is read more often than written. As a consequence, convenience during typing is a bad reason for a coding/naming choice.
Depending on your environment there are other options. You could use your IDE's expansion settings. For example in NetBeans (I am less experienced with other IDEs but imagine there are equivalent options) you could have du+<TAB> expand to ::distributed::utils, if that is something that you use often. Or you could of course just type $KV$ and use seek and replace although that would temporarily break code analysis in your IDE.
Does it matter how I import header files? I've seen double quotes as well as arrows used.
#include <stdlib.h>
#include "Some_Header.h"
Does it matter if they're capitalized a certain way as well? Experimenting around with this, it seems neither matters, but I figure there must be a reason for tutorials doing it the way they do.
Another question is, (coming from Java here), how do I access a class outside the file it was defined in? Say, I have one.cpp and two.cpp.
In one.cpp:
class Something {
...
In two.cpp:
class SomethingElse {
Something *example;
...
Like that? In Java you'd just preface a class name with "public." In C++, wrangling classes seems to be a bit more difficult..
Angle brackets in #include directives means the search path is limited to the "system" include directories. Double quotes mean the search path includes the current directory, followed by the system include directories.
The case of the filename matters when your OS is using a filesystem that is case sensitive. It sounds like you might be using Windows or Mac OS X, where filenames are case insensitive by default.
Angle brackets looks for the header in system header directories (e.g. /usr/include). Quotes is just an absolute or relative pathname, such as /path/to/header.h or ../headers/abc.h.
For accessing classes from other files, just #include the other file with the class. Be sure to structure your program so that no file is included more than once.
First the simple question:
Does it matter if they're capitalized a certain way as well?
In most cases, includes refer to files, and the compiler should be able to locate the file that you are including in the system. For that reason capitalization matters in all systems where the filesystem is case sensitive. If you want to keep a minimum of portability you should be consistent in the name of the files and the include. (All linux and mac os have case sensitive filesystems by default, in windows you can configure NTFS to be case sensitive also)
Now, does it actually matter how the file is named? No, it does not, as long as you are consistent in the inclusions. Also note that it is advisable to follow a pattern to ease the inclusion.
Does it matter how I import header files?
The standard is not really clear to this point, and different implementations followed different paths. The standard defines that they may be different, as the set of locations and order in which the compiler will search for the included file is implementation defined and can differ if the inclusion is with angle brackets or double quotes. If inclusion with quotes fails to locate the file, the compiler must fall back to process the include as if it had been written with angle brackets.
#include <x.h> // search in order in set1 of directories
#include "x.h" // search in order in set2 of directories
// if search fails, search also in set1
That implies that if a file is only present in set1, both types of includes will locate it. If a file is present in set2 but not set1 only the quote include will locate it. If different files with the same name are present in set1 and set2, then each inclusion type will find and include a different file. If two files with the same name are present in the common subset of set1 and set2, but the ordering of the sets is different each inclusion type can locate a different file.
Back to the real world, most compilers will include only the current directory in set2, with set1 being all the system include locations (which can usually be extended with compiler arguments) In these cases, if a file is only present in the current directory, #include "a.h" will locate it, but #include <a.h> will not.
Now, whether that is the common behavior, there are some implied semantics that are idiomatic in C/C++. In general square brackets are used to include system headers and external headers, while double quotes are used to include local files. There is a grey zone on whether a library in the same project should be considered as local or external. That is, even if always including with double quotes will work, most people will use angle quotes to refer to headers that are not part of the current module.
Finally, while no compiler that I know of does it, the standard allows an implementation (compiler) not to produce the standard headers as real files, but process the inclusion of standard headers internally. This is the only case where theoretically #include "vector" could fail to include the definitions of the std::vector class (or any other standard header). But this is not a practical issue, and I don't think it will ever be.
Question 1
Does it matter how I import header
files?
Does it matter if they're capitalized
a certain way as well?
It doesn't matter, but usual practice is,
Use angle brackets for system
headers.
User double quotes for User
defined headers(Your own headers)
Questions 2 & 3
Another question is, (coming from Java
here), how do I access a class outside
the file it was defined in?
You need to place class definition in a header file and include that header file wherever you want to use the class.
For your case, it would look like below.
//One.h
#ifndef ONE_H
#define ONE_H
class Something
{
public:
void doSomething(){}
};
#endif
//Two.cpp
#include "One.h"
class SomethingElse
{
SomeThing *example;
};
Firstly, the #include is a C pre-processor directive and not strictly part of the C++ language as such. You can find out more about it here although this is specifically for the GNU C preprocessor so may be different from what you're using. I think you should always assume case-sensitivity in include files. Not doing so might make it difficult to port you code to a case sensitive OS such as UNIX.
The use of "" or <> is rather subtle as explained above and most time you will notice no difference. Using "" generally searches the current directory first. I tend not to use this as:
I know where my headers are - I always specify them with -I on the compile line.
I've been caught out before when a locally bodged copy of a header overrode the central copy I was hoping to pick up.
I've also noticed some side effects such as when using make to create dependency trees (I can't quite recall the issue - it did treat the different includes differently, following some and not others, but this was about 7 years ago)
Secondly, your question about how to reference functions in other files is answered here/