I had originally asked this question here: Former Question
It appears that what I was asking for was misunderstood. I will try to make this as clear and as brief as possible:
I'm working on a parser that will automatically generate a c++ class and if the names of the header and cpp files are present the parser will write out those files respectively. If they are omitted then the parser will not write any files where it will generate a class automatically based on the information that is pulled in from the file.
What I don't know how to do: Let's say my class's identifier is stored in a std::string how can I extract the text in the string to use that as the class's name. For example:
{
std::string className( "Foo" );
// parser writing class in code
class className { ....
}
This is what I don't know how to do if it can even be done. As stated in my previous question I prefer to stay away from macros but wouldn't mind using templates if needed or some other mechanism.
Conclusion
After reading the comments and the provided answer below; my initial assumption that I didn't mention was in fact proven true. It can not be done. I was suspicious of this, but only wanted to confirm. So this does leave me in having to write out to files in order to create the needed header and or source files at run time.
You can't.
C++ programs cannot modify themselves.
If you want to auto-generate C++ code, do it as an pre-compilation step in your build process.
I myself have a nice Python script generating a ton of C++ classes (and their accompanying boilerplate) each representing one of several "message types" defined by a third party. It's lovely.
Related
I am a tutor and I'm trying to write something to help students learn C++. Suppose I have a .cpp file that includes two .h files, which we will call "solution.h" and "student_answer.h". The "solution.h" file contains a class called "Solution" which implements member functions and variables that solve a problem. Students are to implement their own solution to the same problem in a separate "student_answer.h" file, in a class which we will call "Student".
The .cpp file should then take the two class definitions, "Solution" (the class defined in solution.h) and "Student" (the class defined in student_answer.h), and run the two implementations to verify whether the student answer is correct, and it should provide detailed output in cases where the student answer has a bug. However, I want to be able to hide the contents of the solution.h file (or the "Solution" class) from the students while still providing them with the .cpp file that they can compile and run their own solution with.
Currently, I have something like this:
#include "solution.h"
#include "student_answer.h"
// ...
int main() {
Solution s;
Student a;
// run member functions of s and a, compare results to verify if student
// implementation is correct (and print helpful output if there is a bug)
...
}
Is there a way to do the same thing without having to reveal the solution.h file to the students? Is there a better approach to doing this?
Thanks!
Is there a way to do the same thing without having to reveal the solution.h file to the students?
No.
Best you could do is to not put any implementation details into solution.h and instead provide a pre-compiled library for comparison. That would prevent students from seeing the solution except for the API, which is presumably part of instructions for the student anyway.
This does have a challenge that the pre-compiled library must be compatible with the systems that the students use. This can be solved by instructing the students to use a provided VM or container image.
However, this approach does not prevent the students from implementing their API by delegating to the solution API.
There's really no need to provide the correct solution. Write to solution for yourself only; write tests that are required to pass with either your solution or the student's; Test the tests with your solution; Provide only the tests to the students, not your solution.
Create a static or dynamic library of Solution.h, compile it, and link it with the project. The students now get the header of the solution with declarations, but not definitions.
The library topic is a little bit too complex to explain in one answer. Watch the video from TheChernoProject ( https://www.youtube.com/watch?v=Wt4dxDNmDA8 ) for it.
Another way would be, making the code unreadable (defines) or put it in asm blocks.
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.
I just started on a few C++ tutorials, and I have run into something that I just can't seem to make much sense of.
In C++ it seems people are using a code file and a header file, for me this just seem inconvinient. Why would I want to swap around between two files just to write a simple getter method.
Is it considered the "correct" way to use headers in C++? Or is it just the tutorial I have picked up that uses this?
I get the idea of splitting code to make it look more clean, but is it good for anything else other than that?
Thanks in advance.
There are some reasons for using hpp(header)- and cpp(code)-files. One of them is the following: A library (dll- or so-file) cannot be "used" like a jar-file in java. If you write a library, you have to provide declarations of the classes, methos,... in form of a hpp-file.
Think about using the class you wrote in other files. If you had the class definition in a separate file, you could help the compiler to figure out how to use the class by including the header file in places where you are planning to use this code.
The compiler only needs to know whether you are using the classes right(it does not care about how to run it, until linking), therefore all you need to give the compiler is the declaration of the class(header file), to do the error checking. When you say "include", the preprocessor just copies and pastes the header file contents into the new file, so that the new file now knows how to use the class you wrote.
A header file in c++ stores alot of information, if c++ have been made using every single "header" file in c++ in each program you make, when you then write a function from iostream for example, the program will go through every single header file just to find the right header file. so instead they made the #inlcude function in c++, so you could specify where your functions are from.
And when you create a program you could make own header files, so the code is more nicely set up. and then instead of having to make alot of lines of code in one main source file, you could import others. like if you are making a game, one header file for Animals and in that header file you have a Class for Cats, and one for dogs. having a more clean code.
In C/C++, headers are used to share the class structure (among other things) between classes.
so one can use
include "classFOO.h"
in classBAR.h (or classBAR.cpp) and use classFOO.
I do a lot of c++ programming in vim and I was wondering if there are any plugins or snippets out there that can generate a source file depending on the contents of the header file.
I.E: test.h
class test {
public:
test();
};
and then going into the test.cpp file and typing "src" and expanding it (using some sort of snippet plugin like UltiSnips) it would look in the test.h file for the funcions and (in this case) make:
test::test() {
//code
}
I got this idea from Derek Wyatt's blog and he does this using XPTemplate so I thought it would be great to do the same in UltiSnips.
Use the xptemplate plugin.
Examples:
http://www.derekwyatt.org/wp-content/uploads/2009/08/my.cpp.xpt.vim
http://www.derekwyatt.org/vim/working-with-vim-and-cpp/cpp-snippets
lh-cpp offers a :GOTOIMPL function that analyses the prototype of a given function, and either jumps to the associated definition or generates it on-the-fly. [NB: it knows what to do with virtual, static, namespace/embedded classes, return type, modifiers, and so on (except templates yet)]
Regarding how to parse a header file and generate all associated functions, the exact same question has been asked on vim mailing list 2-3 weeks ago where another solution has been given (protodef, that you have read about).
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.