ignore a main in a header file - c++

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.

Related

conditionally integrate functionality from one header into another if it's included (is this even necessary?)

Maybe I'm thinking about this the wrong way because I spent so many years on C# away from C++ and I'm a bit rusty. I forget how good selective linking is.
This is really a multi-part question, and I'll start by describing the big picture.
I am building a JSON parser and query engine for low memory environments like IoT devices. They don't have a ton of space for code so I want the end developer to be able to only include parts of my library they intend to use. The pull parser is the core of the library so that's a given, but you might not need the in-memory trees.
Currently, lacking a better way, I have a #define HTCW_JSONTREE which i define in one header. It gets picked up by a 2nd header and a function is included in the 2nd header that depends on code in the first header.
#include "JsonTree.h" // optional
#include "JsonReader.h" // if JsonTree.h above is included
// extra functionality will be available from JsonReader
basically a parseSubtree() function that returns an in-memory tree will be available if you include both headers, but won't if you don't include JsonTree.h. It smells.
First of all, is this necessary, or can I just unconditionally include all the functionality and expect that parseSubtree() will never get linked in if its never used?
Second, if it is necessary, what is a better way to do it? Right now the includes are order dependent and the code reeks. I want to change it. Basically it's just in there now until I figure out something better because it's easier to remove than it would have been to add later if it turns out i need it.
Thanks in advance.
Here's more of what the code looks like:
From JsonTree.hpp by way of JsonTree.h:
#ifndef HTCW_JSONTREE_HPP
#define HTCW_JSONTREE_HPP
#define HTCW_JSONTREE
#include <cinttypes>
...
from JsonReader.hpp by way of JsonReader.h:
#ifdef HTCW_JSONTREE
JsonElement* parseSubtree(mem::MemoryPool& pool,JsonParseFilter* pfilter = nullptr,mem::MemoryPool* pstringPool=nullptr,bool poolValues=false) {
...
#endif
Where JsonElement comes from JsonTree.h as well. parseSubtree is my integration point between the two areas of functionality
First of all, is this necessary
Absolutely not.
Or can I just unconditionally include all the functionality and expect that parseSubtree() will never get linked in if its never used?
You totally can. That's how all libraries in existence have worked from day one.

Protecting certain include locations

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...

C++ #define in main, how to get other .cpp files to see it?

Good afternoon all,
I'm writing a program to read license plates that has 11 files currently:
Main.cpp
DetectPlates.h
DetectPlates.cpp
DetectChars.h
DetectChars.cpp
PossiblePlate.h
PossiblePlate.cpp
PossibleChar.h
PossibleChar.cpp
Preprocess.h
Preprocess.cpp
I have a feature allowing showing the intermediate processing steps, or not. Current this is implemented by having a global variable in Main.cpp as follows:
// global variables ///////////////////////////////////////////////////////////////////////////////
const bool blnShowSteps = false;
Then in DetectPlates.h and DetectChars.h, I have the following:
// external global variables //////////////////////////////////////////////////////////////////////
extern const bool blnShowSteps;
So in either DetectPlates.cpp or in DetectChars.cpp I can do something like the following:
if (blnShowSteps) {
cv::imshow("1a", imgGrayscaleScene);
cv::imshow("1b", imgThreshScene);
}
This is done many times in both DetectPlates.cpp and in DetectChars.cpp. So far I have used a global variable as above because I was translating this from a Visual Basic.NET version where the conditional looked at the state of a check box on a form and a global variable was an easy translation to start with.
To make this more "C++ish" I would like to change the global variable to conditional compilation. For example, in Main.cpp I would like to do:
#define SHOW_STEPS // NOTE: comment this line out, or not, to show or not show steps
Then in DetectPlates.cpp or DetectChars.cpp:
#ifdef SHOW_STEPS
cv::imshow("1a", imgGrayscaleScene);
cv::imshow("1b", imgThreshScene);
#endif
The problem is how do I implement this? If I #include "Main.cpp" in DetectPlates.h and/or DetectChars.h I get various errors depending on if I used a multiple include guard in Main.cpp or not, but either way I do not get a compile and also this violates the general practice rule of never including a .cpp file.
One possible answer seems to be adding another .h file, called "MyDefines.h" or similar, with only one line:
// MyDefines.h - single line .h file ??
#define SHOW_STEPS // NOTE: comment this line out to not show steps
But this is not an elegant solution for at least two reasons, for one adding an additional .h file to add one line seems poor, and also that would take the #define SHOW_STEPS out of the beginning of Main.cpp where it would logically be.
Another possible solution would seem to be to add a Main.h file, with the function prototypes and other stuff that is at the top of Main.cpp currently, and then to also add the #define SHOW_STEPS line. This is also not a very elegant solution either since I would be adding an entire .h file to add one line, most C++ programs do not have a Main.h file, and this would still remove #define SHOW_STEPS from being just above function main() where most people would intuitively look when figuring out the flow of the program.
Is there a way to do this where the "#define SHOW_STEPS" line would be in Main.cpp but still be seen in DetectPlates.cpp and DetectPlates.cpp?
As you suspected - place the definition in a header file (.h), and include it wherever necessary.
Either that, or don't use compiler tricks, make a configuration class, and pass the configuration object into the relevant part(s) of the program. Have the configuration class read from a file or be initialised in a relevant way.
Edit: Just to comment on, "To make this more "C++ish" I would like to change the global variable to conditional compilation". Both are pretty dodgy practises. Decent code design is probably what you're looking for!
If you introduce #defines to make your code more "C++ish", you're doing something very wrong.
You don't need to explictly remove the if's at all, the compiler can do this for you, given better circumstances. To start with, change your global variable from extern to static in a header.
...That should be enough. If in doubt, check the asm output.
Make it be defined for your whole project. Like adding -DSHOW_STEPS to GCC command line.

Is there any situation where you wouldn't want include guards?

I know why include guards exist, and that #pragma once is not standard and thus not supported by all compilers etc.
My question is of a different kind:
Is there any sensible reason to ever not have them? I've yet to come across a situation where theoretically, there would be any benefit of not providing include guards in a file that is meant to be included somewhere else. Does anyone have an example where there is an actual benefit of not having them?
The reason I ask - to me they seem pretty redundant, as you always use them, and that the behaviour of #pragma once could as well just be automatically applied to literally everything.
I've seen headers that generate code depending on macros defined before their inclusion. In this case it's sometimes wanted to define those macros to one (set of) value(s), include the header, redefine the macros, and include again.
Everybody who sees such agrees that it's ugly and best avoided, but sometimes (like if the code in said headers is generated by some other means) it's the lesser evil to do that.
Other than that, I can't think of a reason.
#sbi already talked about code generation, so let me give an example.
Say that you have an enumeration of a lot of items, and that you would like to generate a bunch of functions for each of its elements...
One solution is to use this multiple inclusion trick.
// myenumeration.td
MY_ENUMERATION_META_FUNCTION(Item1)
MY_ENUMERATION_META_FUNCTION(Item2)
MY_ENUMERATION_META_FUNCTION(Item3)
MY_ENUMERATION_META_FUNCTION(Item4)
MY_ENUMERATION_META_FUNCTION(Item5)
Then people just use it like so:
#define MY_ENUMERATION_META_FUNCTION(Item_) \
case Item_: return #Item_;
char const* print(MyEnum i)
{
switch(i) {
#include "myenumeration.td"
}
__unreachable__("print");
return 0; // to shut up gcc
}
#undef MY_ENUMERATION_META_FUNCTION
Whether this is nice or hackish is up to you, but clearly it is useful not to have to crawl through all the utilities functions each time a new value is added to the enum.
<cassert>
<assert.h>
"The assert macro is redefined according to the current state of NDEBUG each time that
<assert.h> is included."
It can be a problem if you have two headers in a project which use the same include guard, e.g. if you have two third party libraries, and they both have a header which uses an include guard symbol such as __CONSTANTS_H__, then you won't be able to successfully #include both headers in a given compilation unit. A better solution is #pragma once, but some older compilers do not support this.
Suppose you have a third party library, and you can't modify its code. Now suppose including files from this library generates compiler warnings. You would normally want to compile your own code at high warning levels, but doing so would generate a large set of warnings from using the library. You could write warning disabler/enabler headers that you could then wrap around the third party library, and they should be able to be included multiple times.
Another more sophisticated kind of use is Boost's Preprocessor iteration construct:
http://www.boost.org/doc/libs/1_46_0/libs/preprocessor/doc/index.html
The problem with #pragma once, and the reason it is not part of the standard, is that it just doesn't always work everywhere. How does the compiler know if two files are the same file or not, if included from different paths?
Think about it, what happens if the compiler makes a mistake and fails to include a file that it should have included? What happens if it includes a file twice, that it shouldn't have? How would you fix that?
With include guards, the worst that can happen is that it takes a bit longer to compile.
Edit:
Check out this thread on comp.std.c++ "#pragma once in ISO standard yet?"
http://groups.google.com/group/comp.std.c++/browse_thread/thread/c527240043c8df92

Ways not to write function headers twice?

I've got a C/C++ question, can I reuse functions across different object files or projects without writing the function headers twice? (one for defining the function and one for declaring it)
I don't know much about C/C++, Delphi and D. I assume that in Delphi or D, you would just write once what arguments a function takes and then you can use the function across diferent projects.
And in C you need the function declaration in header files *again??, right?. Is there a good tool that will create header files from C sources? I've got one, but it's not preprocessor-aware and not very strict. And I've had some macro technique that worked rather bad.
I'm looking for ways to program in C/C++ like described here http://www.digitalmars.com/d/1.0/pretod.html
Imho, generating the headers from the source is a bad idea and is unpractical.
Headers can contain more information that just function names and parameters.
Here are some examples:
a C++ header can define an abstract class for which a source file may be unneeded
A template can only be defined in a header file
Default parameters are only specified in the class definition (thus in the header file)
You usually write your header, then write the implementation in a corresponding source file.
I think doing the other way around is counter-intuitive and doesn't fit with the spirit of C or C++.
The only exception is can see to that is the static functions. A static function only appears in its source file (.cor .cpp) and can't (obviously) be used elsewhere.
While I agree it is often annoying to copy the header definition of a method/function to the source file, you can probably configure your code editor to ease this. I use Vim and a quick script helped me with this a lot. I guess a similar solution exists for most other editors.
Anyway, while this can seem annoying, keep in mind it also gives a greater flexibility. You can distribute your header files (.h, .hpp or whatever) and then transparently change the implementation in source files afterward.
Also, just to mention it, there is no such thing as C/C++: there is C and there is C++; those are different languages (which indeed share much, but still).
It seems to me that you don't really need/want to auto-generate headers from source; you want to be able to write a single file and have a tool that can intelligently split that into a header file and a source file.
Unfortunately, I'm not aware of any such tool. It's certainly possible to write one - but you'd need a given a C++ front end. You could try writing something using clang - but it would be a significant amount of work.
Considering you have declared some functions and wrote their implementation you will have a .c/cpp file and a header .h file.
What you must do in order to use those functions:
Create a library (DLL/so or static library .a/.lib - for now I recommend static library for the ease of use) from the files were the implementation resides
Use the header file (#include it) (you don't need to rewrite the header file again) in your programs to obtain the function definitions and link with your library from step 1.
Though >this< is an example for Visual Studio it makes perfect sense for other development environments also.
This seems like a rudimentary question, so assuming I have not mis-read,
Here is a basic example of re-use, to answer your first question:
#include "stdio.h"
int main( int c, char ** argv ){
puts( "Hello world" );
}
Explanation:
1. stdio.h is a C header file containing (among others) the definition of a function called puts().
2. in main, puts() is called, from the included definition.
Some compilers (including gcc I think ) have an option to generate headers.
There is always very much confusion about headers and source-files in C++. The links I provided should help to clear that up a little.
If you are in the situation that you want to extract headers from source-file, then you probably went about it the wrong way. Usually you first declare your function in a header-file, and then provide an implementation (definition) for it in a source-file. If your function is actually a method of a class, you can also provide the definition in header file.
Technically, a header file is just a bunch of text that is actually inserted into the source file by the preprocessor:
#include <vector>
tells the preprocessor to insert contents of the file vector at the exact place where the #include appears. This really just text-replacement. So, header-files are not some kind of special language construct. They contain normal code. But by putting that code into a separate file, you can easily include it in other files using the preprocessor.
I think it's a good question which is what led me to ask this: Visual studio: automatically update C++ cpp/header file when the other is changed?
There are some refactoring tools mentioned but unfortunately I don't think there's a perfect solution; you simply have to write your function signatures twice. The exception is when you are writing your implementations inline, but there are reasons why you can't or shouldn't always do this.
You might be interested in Lazy C++. However, you should do a few projects the old-fashioned way (with separate header and source files) before attempting to use this tool. I considered using it myself, but then figured I would always be accidentally editing the generated files instead of the lzz file.
You could just put all the definitions in the header file...
This goes against common practice, but is not unheard of.