Eclipse-CDT: Use Namespace in automatic generated include-guards - eclipse

Is it possible (and how) to add the namespace in the name of the automatic generated include guards in Eclipse CDT, when creating a new class using the .hpp/.cpp templates?
For me Eclipse generates a new class with a namespace nicely, but the include guards do not contain the namespace, so if the same header file exists twice in two different directories, only one can be included.
In my case the name of the namespace, the Eclipse project name and the name of the source directory are all the same, so these could be alternatives as prefix for the include guard.

So in the Preferences dialog under C/C++ -> Code Style -> Code Templates you can modify the template to be closer to what you need, for example if you need the namespace in the guard, you can do something like.
${filecomment}
#ifndef ${namespace_name}_${include_guard_symbol}
#define ${namespace_name}_${include_guard_symbol}
${includes}
${namespace_begin}
${declarations}
${namespace_end}
#endif /* ${namespace_name}_${include_guard_symbol} */`

There's a hidden preference you can set to get at least the file's path or a uuid in there instead of just CLASSNAME_H_. See my full answer here.

Related

How to set Eclipse CDT to index / resolve std files

I have the following piece of code:
#include <iostream>
using namespace std;
int main()
{
vector<int> v; //Symbol vector could not be resolved
return 0;
}
The IDE complains about "vector": Symbol vector could not be resolved.
If I right click the "vector" keyword -> Source -> Add Include, nothing happens.
If I manually add #include <vector>, then everything is just fine, the file is indexed and I can use its member functions.
However, I expect the IDE to generate these include files for me, instead of manually adding them. How to setup eclipse to work like this?
I am using Ubuntu 16.04 and Eclipse CDT Neon.
This will only work if another file in your project already includes <vector>.
The way Add Include works is it searches the project's index for the name it's invoked on. If it finds a binding (function, type, etc.) corresponding to that name in the index, it sees what file declares that binding, and then includes that file for you.
For this to work, the binding corresponding to the name must be in the index already. For bindings declared in files external to your project (such as standard library headers), that will only be the case if the external file is already included by some file in your project.
#HighCommander4 - I noticed, through practice, the indexer behaves like in your description. There must be another file which already includes vector in order to have it in the index.
Given this behavior we can do the following:
One workaround is to have a dummy cpp file including <bits/stdc++.h>. Most of the stl headers are there. The header is available for GCC. For MSVC we can simply copy the content of into this dummy cpp file.
Another workaround is to add a linked folder to the location of the stl, in my case this is /usr/include/c++/5. In this case the whole stl library gets indexed from the very beginning.

What is the correct way to embed a resource in a reusable MFC class?

I am writing a C++ (MFC in particular) class which uses an external .gif image file and produces another image file after some processing. It would be nice if the initial image could be embedded in the code somehow. I have read in MSDN about using multiple .rc files and the whole thing seems quite complicated.
I would like to know from people who have gone through this before how to handle this problem.
EDIT : Sorry I was not clear. The class I am writing should be standalone, so I could use it again. If I put the image in a resource file, then the class will not compile if used in a fresh project.
You cannot embedd MFC resources inside a class or similar C++ container. They can only be embedded in DLL or EXE files - in a separate section of the produced binary. Since you want your class to be reusable, you must put it in a DLL. Hence, you must tag your class with the AFX_EXT_CLASS keyword.
There are two solutions.
Solution #1:
Create an MFC DLL project (MFC Extension DLL). Call it MyLibrary or whatever.
Put all your standalone classes in this DLL.
Embed all necessary resources.
Let your classes load resources from the HINSTANCE of your DLL as described below.
There are several ways to retrieve the HINSTANCE of your DLL. If you ask me, the best solution is to grab it in DllMain. This is done automatically if you choose the MFC Extension DLL configuration:
static AFX_EXTENSION_MODULE MyLibDLL = { NULL, NULL }; // Make this variable global!
// Then access the hInstance as follows:
LoadResource(MyLibDLL.hModule, ...)
Solution #2:
Store your resource as a byte buffer. Or better, convert it to Base64 and store it as an ASCII string. But remember not to blow the stack! Keep your resources small or increase the stack size in your project settings. Example:
const char *encodedResource = "SGVsbG8gd29ybGQh";
char *data = decode(encodedResource);
foo(data);
In the solution explorer go to resource view, Right click and click Add Resource then click Import and add the gif file. Now you can use your Resource ID to access the gif file in your code.
Just adding the file to a resource doesn't embed the file in the actual resource file it just links to the file. If you open your .rc file you'll see it says something like:
IDB_GIF_MYIMAGE GIF "artwork\\mygif.gif"
During the compilation face the resource will be included in the EXE, which you reference using the resource id IDB_GIF_MYIMAGE. You can reference the same file in other projects without having to duplicate the file.
To embed an image (or any other type of binary data) into your class without using resource files, use the bin2c utility, for example you can download it from here: http://www.opensource.apple.com/source/libpcap/libpcap-16/libpcap/msdos/bin2c.c . Running this on a file will produce what is basically a static array with the bytes of the file as members of that array. Stuff this array into a .h file (or put it in the header of your class, or make it a static member...) and then you will have that file available in-memory without having to use LoadResource() and its brethren.
If you want to use this with CImage::Load(), you will have to write your own class that derives from IStream, and implement a few of the methods in a way so that they 'read' from memory. I don't know of any ways to let CImage decode an image from an in-memory representation of a gif file.
I think the best solution is just to document that to use the class you must also import to your project a certain .gif file and give it a certain expected identifier (e.g. IDB_MYCLASS_MYGIF). You can then use the preprocessor to detect if the resource has been correctly added, e.g.:
#ifndef IDB_MYCLASS_MYGIF
#error Make sure you import mygif.gif to the project. See docs for more info.
#endif
This will prevent the class compiling until the user imports the image properly. Alternatively you could just use #ifdefs to fall back to code which does not use the default image if it is not provided.
Have a look at the CRuntimeDialog class presented in http://www.codeproject.com/Articles/5371/ToDoList-6-5-4-Feature-Release-An-effective-and-fl . It provides a way to create a dialog from the string that makes up the resource definition.

How do I include files with no extension for my Xtext DSL?

By default Xtext allows to specify a single extension for DSL files when creating a new project. However, it is possible to add more extensions for a single DSL as described in Xtext FAQ. But I couldn't get it working with files with no extension at all.
A typical example is a makefile for Make build system. One can use Makefile, GNUmakefile and *.mk names, and Eclipse will open the same editor for such files.
I want to get Xtext to recognize both *.mydsl files and a file named Mydsl.
I tried to add
filenames="Mydsl"
attribute to editor node of org.eclipse.ui.editors extension point in plugin.xml of my UI project. This enables Eclipse to open Mydsl files in the proper editor. But Xtext does not index these files and reports linking errors when I try to refer an element defined in Mydsl from any other file.
Is there a way to enable Xtext to process source files with fixed name but with no extension as well as regular files?
UPD. 1
Accordingly to Sebastian's answer I tried to specify a custom content type in plugin.xml of the main project:
<extension
point="org.eclipse.core.contenttype.contentTypes">
<content-type
base-type="org.eclipse.core.runtime.text"
file-extensions="mydsl"
file-names="Mydsl"
id="org.xtext.example.mydsl.contentType"
name="My Language"
priority="normal">
</content-type>
</extension>
And binding it as follows:
<extension
point="org.eclipse.xtext.content_resourceServiceProvider">
<resourceServiceProvider
class="org.xtext.example.mydsl.MyDslResourceServiceProvider"
contentTypeIdentifier="org.xtext.example.mydsl.contentType">
</resourceServiceProvider>
</extension>
But I still get linking errors as described above. I also added breakpoints into all methods of MyDslResourceServiceProvider and it seems that it doesn't even get instantiated or somehow invoked.
I also tried to move these extensions to the UI project but with no effect too.
UPD. 2
Finally, I've done it.
Steps to get things work in a nutshell:
Define new content type using org.eclipse.core.contenttype.contentTypes extension point
Create a content handler by extending org.eclipse.emf.ecore.resource.impl.PlatformContentHandlerImpl class and override canHandle(URI) method to return true if and only if the argument is not null
Register it with org.eclipse.emf.ecore.content_handler
Create a new resource service provider with canHandle(URI) returning true always. One can extend org.eclipse.xtext.resource.impl.DefaultResourceServiceProvider and override the corresponding method
In the UI project bind it to org.eclipse.xtext.content_resourceServiceProvider, do not forget to specify an extension factory before the class name
In the UI project register org.eclipse.xtext.resource.IResourceFactory as org.eclipse.emf.ecore.content_parser, again with the extension factory
Add content type bindings to org.eclipse.ui.editors, org.eclipse.compare.contentViewers and org.eclipse.compare.contentMergeViewers
Depending on whether you need an old extension binding or not, remove org.eclipse.emf.ecore.extension_parser and org.eclipse.xtext.extension_resourceServiceProvider extensions
A change set (applied to a fresh project) for my case can be found here.
You could try to exploit the extension point for resource service providers and resource factories. It allows to register services / factory either by file extension or by content type. I think the latter should work if you provide a suitable content type for your files.

How to customize eclipse CDT code templates

I need the code I am writing for a project to match some style guidelines. However the standard templates included with CDT don't match this style. Especially the layout of the header guards is not the way it should be. I had a look at the template and for my Eclipse it looks like this:
${filecomment}
#ifndef ${include_guard_symbol}
#define ${include_guard_symbol}
${typecomment}
${declarations}
#endif /* ${include_guard_symbol} */
So I am guessing the variable ${include_guard_symbol} is set somewhere in the CDT, but is it possible to change this setting without needing to modify the CDT itself?
On a slightly different, but related note:
Is it possible to add your own templates, so you just could add new files of other types (test-cases, specialized classes etc) using the normal new dialog for the project?
We've had a similar struggle on our project. One solution is to throw out ${include_guard_symbol} in the template all together, and define it yourself, possibly using some of the other predefined variables. Something like this:
${filecomment}
#ifndef MyProject_${file_base}_h
#define MyProject_${file_base}_h
${typecomment}
${declarations}
#endif /* MyProject_${file_base}_h */
So for a header file named inc/Foo.h, the include guard would be inserted like this:
#ifndef MyProject_Foo_h
#define MyProject_Foo_h
Unfortunately, there doesn't seem to be a way to customize much beyond that. For example, if I defined a class nested in a namespace, I might want to put the namespace as part of the include guard. I can't find a way to do that in eclipse, currently.
So in the Preferences dialog under C/C++ -> Code Style -> Code Templates you can modify the template to be closer to what you need, for example if you need the namespace in the guard, you can do something like.
${filecomment}
#ifndef ${namespace_name}_${include_guard_symbol}
#define ${namespace_name}_${include_guard_symbol}
${includes}
${namespace_begin}
${declarations}
${namespace_end}
#endif /* ${namespace_name}_${include_guard_symbol} */

How does XCode handle #import header statements in with multiple targets?

I have an XCode project with 2 targets (both are iPhone apps sharing 95% of the same code).
However, one module isn't "shareable"; the implementations are too different.
My solution (that is not working) was to add 2 subdirectories to my Classes/ folder in my project directory - one for each target. In each directory, I've placed a view controller class, called ExampleSentencesViewController. Of course, each file is compiled as part of only one of the targets - I'm looking for an "automatic switching" of which implementation to use based on the target.
Inside each target's settings, I added each directory to the "Header Search Paths" setting (each path for each target).
Oddly, it only compiles for the original target. The target I added later won't compile, claiming that I've included the same header twice (there ARE two files, to be fair). How do I get XCode to forget about the original header??
I've tried deleting the .h files out of my project, but that does not seem to help.
Any help is appreciated.
fully qualify the header paths in the separate implementation files, based on one of your defined search directories:
#include <MONProject/Source/ExampleSentencesViewController.h>
vs
#include <MONSecondProject/Source/ExampleSentencesViewController.h>
update based on clarification:
ideally, you'd create a static library for the shared code.
for a simple case... you could take the direct approach by populating a header in your project's root, named ExampleSentencesViewController.h, and populating it like so:
/* you must define either MON_BUILD_MON_FIRST_PROJECT or MON_BUILD_MON_SECOND_PROJECT at the target level */
#if (defined(MON_BUILD_MON_FIRST_PROJECT) && defined(MON_BUILD_MON_SECOND_PROJECT))
#error invalid configuration: you cannot specify both projects to be compiled
#elif defined(MON_BUILD_MON_FIRST_PROJECT)
/* some fully qualified path: */
#include <MONFirstProject/ExampleSentencesViewController.h>
#elif defined(MON_BUILD_MON_SECOND_PROJECT)
/* some other fully qualified path: */
#include <MONSecondProject/ExampleSentencesViewController.h>
#else
#error uh... which project are you trying to build?
#endif
or you could just use these defines to conditionally enable/disable the interface and implementation of the classes with duplicate names (and then just include them both in the project's declaration of:
/* MONFirstProject/ExampleSentencesViewController.h> */
#if defined(MON_BUILD_MON_FIRST_PROJECT)
#interface ExampleSentencesViewController : NSViewController
/* ... */
#end
#endif
…but this will require to include both headers in your distribution (if applicable).
some of the finer details of inclusion can vary based on how you've declared your search paths (e.g., are they recursive or not?) and whether you use copy headers build phases in your xcodeproj. maintaining both projects which share code can become messy if you've been too relaxed in your include directives, discovery options, preprocessor declarations (conditional compilation/visibility) and/or build configurations so... that's why i recommend a library for the shared bits. this conditional stuff (in the two previous examples) is error prone and doesn't evolve or scale well. doing this is also a good way to confuse other tools in the development toolkit.
in fact, i prefer this over the preprocessor (assuming you're able to distribute both classes):
- (UIViewController *)newViewControllerForMyAwesomeView {
if (IsAppMONFirstProject) {
return [[MONFirstProjectViewController alloc] init...];
}
else if (IsAppMONSecondProject) {
return [[MONSecondProjectViewController alloc] init...];
}
else {
assert(0 && "definitely break up your code, now that it is referenced by 3 or more projects");
return 0;
}
}
if you're merely maintaining two versions of the same title, then practices will be much different.
anyways... this should be enough ideas to solve your problem - you just have to determine the lesser evil.