Multiple Files to a project in c++ - c++

I have been writing code for a little while now and I recently found out how to create classes in different files and include them in main, along with more cpp files including the definitions of those classes. I was wondering when this is really needed, my code isnt normally that long. Should I use this now as a beginning when my code is only a few hundred lines or less or are the multiple files used with alot more code. In cases like this with such a short code I could probably find it easier just to stick to the main cpp. Any thoughts on this?

Bad habits are easy to learn and hard to unlearn. Why not do it the right way from the beginning?

I advise for the sake of organization that you should create a new set of files - .h and .cpp - for each new functionality you want to add. That doesn't mean create a new file for ever class you want to have. As an example, you can define a Sound class and a SoundManager class in the same header if you want. It's easier to find and edit a faulty piece of code when it isn't all jumbled up with other code in a catch-all file.
When you get to multi-thousand or even multi-million line projects (which I'm sure you will sooner or later), you will obviously be in for a world of pain if you shove it all into one file. Like David Schwartz said, it's better learn it correctly the first time than to relearn it correctly the second time.

If you have different parts of your code in different files, then you can open each file in a new editor window and view them side by side instead of having to jump up and down in the same file
Yeah, I know that some editors have a "split window" mode, but those don't play nicely with multiple monitors, etc, etc

Related

Extract comment written in Chinese and translate them into English using some script

I have a C++ project in which comments of source code are in Chinese language, now I want to convert them into English.
I tried to solve using google translator but got an Issue: Whole CPP files or header didn't get converted, also I have found the name of the struct, class etc gets changed. Sometimes code also gets modified.
Note: Each .cpp or .h file is less than 1000 lines of code.But there are multiple C++ projects each having around 10 files. Thus I have around 50 files for which I need to translate Chinese text to English.
Well, what did you expect? Google Translate doesn't know what a CPP file is and how to treat it. You'll have to write your own program that extracts comments from them (not that hard), runs just those through Google Translate, and then puts them back in.
Mind you, if there is commented out code, or the comments reference variable names, those will get translated too. Detecting and handling these cases is a lot harder already.
Extracting comments is a lexical issue, and mostly a quite simple one.
In a few hours, you could write (e.g. with flex) some simple command line program extracting them. And a good editor (such as GNU emacs) could even be configured to run that filter on selected code chunks.
(handling a few corner cases, such as raw string literals, might be slightly more difficult, but these don't happen often and you might handle them manually)
BTW, if you are assigned to work on that code, you'll need to understand it, and that takes much more time than copy&pasting or editing each comments manually.
At last, I am not sure of the quality of automatic translation of code comments. You might be disappointed. Also, the code names (of functions, of classes, of variables, etc...) matter a lot more.
Perhaps adding your comments in English could be wiser.
Don't forget to use some version control system. You really need one (e.g. git)
(I am not convinced that extracting comments for automatic translation would help your work)
First separate both comment and code part in different file using python script as below,
import sys
file=sys.argv[1]
f=open(file,"r")
lines=f.readlines()
f.close()
comment=open("comment.txt","w+")
code=open("code.txt","w+")
for l in lines:
if "//" in l:
comment.write(l)
code.write("\n")
else:
code.write(l)
comment.write("\n")
comment.close()
code.close()
Now translate comment.txt with google translator and then use
paste code.txt comment_en > source
where comment_en is translated comment in english.

Using a Main program to edit all program headers in a directory?

I have frequently encountered the following issue in my day to day programming at the office where files can be reused from one project to the next, but the header information needs to be updated for each file, when you are dealing with hundreds of files updating them all manually is a pain, and a waste of resources.
Ideally what I would like is a program that contains a standard header with attributes like author, project code, creation date etc, that I can manually update and when executed it will add this information to all the files/programs in a directory. We use a standard header, which cover the first 20 lines of each program and each attribute is on a certain line, or can be searched for in order to replace it.
For the most part I would like to develop this myself, but any starting point as to how to apply said header to the first 20 lines of each program and how to apply it to each file in a directory. I want to add other functionality later for tracking purposes etc, but for now any help in getting started would be awesome.
I'm a big fan of using keyboard macros to generate header shells. So when I hit CTRL-H, I get a header block comment with the sort of information you described, including my name and today's date. If the assumption is that you will have to manually type something into a header for every program for every project (e.g. a revision note or whatever), then automatically adding 100 header shells doesn't save you much more than the keyboard macro approach.
That said, yes, you could do it with SAS using file statement or whatever. Could probably do it with any good text editor.
And of course a better solution would be to get a version control system.
I wouldn't modify the programs in the directory this way, but rather use %include files. We've done that on projects before, where you have a single program that includes libnames and such, and then you have
%include('header.sas');
or whatever in every program you write in that project. Modifying the code programmatically like this is a bad idea, both because you might not have the most up to date version of the headers, and because it risks damaging the programs if you do it incorrectly). Putting it as an include is easy, avoids replicating the same code 20 times (with possibility of error), and guarantees up-to-date code.
In your case, you can modify the 'header' file for the new day, and assuming you've set things up properly (which it sounds like you have), then the 100 or whatever other programs all can stay the same, unchanged, just including the updated header (automatically). This has the added advantage that you don't make lots of tiny changes to the programs, meaning you know when a meaningful update to the program occurred (as opposed to just a daily run).
In general, this modular approach is superior - divorcing the 'individual run' part of a program/process from the main part - because of these reasons, and because it makes it easier to reuse programs for other purposes as well if you have it set up so the module is already prepared and just needs a header file in the same directory to automatically run. (You can get the name of the current program and its path; if you need that, comment with what mode you use - batch or interactive - and what OS you are in).
This is also one of the places where the Enterprise Guide model is a bit better; there you have all of your project-related files in one project file (.egp), so you don't have to do even this - the project itself can have an autoexec process flow (which runs first, to set libnames and such) and can have notes/author/etc.
This should work. If a line starts with "Author:" it replaces the line with "Author: ME, ONLY ME!!!".
If you are on Windows, change all the forward slashes ("/") to backward slashes ("\").
%let infolder=/folder/where/sas/programs/are;
%let outfolder=/folder/where/new/sas/programs/are/going;
filename dummy temp;
data _null_;
attrib currentinfile currentoutfile length=$32000;
infile "&infolder/*.sas" filename=currentinfile lrecl=32000;
input;
currentoutfile="&outfolder./"!!scan(currentinfile,-1,"/");
file dummy filevar=currentoutfile lrecl=32000;
if index(_infile_,"Author:")=1 then put "Author: ME, ONLY ME!!!";
else put _infile_;
run;

Loading a text file in to memory and analyze its contents

For educational purposes, I would like to build an IDE for PHP coding.
I made a form app and added OpenFileDialog ..(my c# knowledge was useful, because it was easy ... even though without intelisense!)
Loading a file and reading lines from it is basically the same in every language (even PERL).
But my goal is to write homemade intelisense. I don't need info on the richtextBox and the events it generates, endline, EOF, etc, etc.
The problem I have is, how do I handle the data? line for line?
a struct for each line of text file?
looping all the structs in a linked list? ...
while updating the richtextBox?
searching for opening and closing brackets, variables, etc, etc
I think Microsoft stores a SQL type of database in the app project folders.
But how would you keep track of the variables and simulate them in some sort of form?
I would like to know how to handle this efficiently on dynamic text.
Having never thought this through before, it sounds like an interesting challenge.
Personally, I think you'll have to implement a lexical scanner, tokenizing the entire source file into a source tree, with each token also having information about it mapping the token to a line/character inside of the source file.
From there you can see how far you want to go with it - when someone hovers over a token, it can use the context of the code around it to be more intelligent about the "intellisense" you are providing.
Hovering over something would map back to your source tree, which (as you are building it) you would load up with any information that you want to display.
Maybe it's overkill, but it sounds like a fun project.
This sounds to be related to this question:
https://softwareengineering.stackexchange.com/questions/189471/how-do-ide-s-provide-auto-completion-instant-error-checking-and-debugging
The accepted answer of that question recommends this link which I found very interesting:
http://msdn.microsoft.com/en-us/magazine/cc163781.aspx
In a nutshell, most IDEs generate the parse tree from the code and that is what they stores and manage.

C++ IDE feature: Synchronized viewing columns for headers and implementation files?

Modern screens have large resolutions, fitting two or three columns of 80-column code easily. C++ basically requires that you separate your code into .hpp and .cpp files.
So, to utilize this space, why not automatically open the .cpp file in a second column when you open a .hpp file (and vice versa)? This obviously wouldn't work for extreme cases, although for a lot of projects there is a direct correspondence between the filenames that would be easy to determine. To me, this seems like a very reasonable use of this space, and it's hard to imagine it hasn't been done.
Is there an IDE that does this? A plugin? Or, why do you think it can't be done?
If you're in Visual Studio, a plugin (Visual Assist X), which is already very nice to have for C++ projects has a similar feature. It's not completely automatic, but all you have to do is press Alt+o and it will open the other file in the set. That is, if you're .hpp pressing the key will open the .cpp, and vice versa.
Their website demonstrates how this works in a video. It also works for things like XAML/Code Behind files, Windows Forms/Code files, etc. (Basically anywhere files operate in pairs, that key combo switches to the other file in the pair)

C++ Directory Restructuring

I have a source code of about 500 files in about 10 directories. I need to refactor the directory structure - this includes changing the directory hierarchy or renaming some directories.
I am using svn version control. There are two ways to refactor: one preserving svn history (using svn move command) and the other without preserving. I think refactoring preserving svn history is a lot easier using eclipse CDT and SVN plugin (visual studio does not fit at all for directory restructuring).
But right now since the code is not released, we have the option to not preserve history.
Still there remains the task of changing the include directives of header files wherever they are included. I am thinking of writing a small script using python - receives a map from current filename to new filename, and makes the rename wherever needed (using something like sed). Has anyone done this kind of directory refactoring? Do you know of good related tools?
If you're having to rewrite the #includes to do this, you did it wrong. Change all your #includes to use a very simple directory structure, at mot two levels deep and only using a second level to organize around architecture or OS dependencies (like sys/types.h).
Then change your make files to use -I include paths.
Voila. You'll never have to hack the code again for this, and compiles will blow up instantly if something goes wrong.
As far as the history part, I personally find it easier to make a clean start when doing this sort of thing; archive the old one, make a new repository v2, go from there. The counterargument is when there is a whole lot of history of changes, or lots of open issues against the existing code.
Oh, and you do have good tests, and you're not doing this with a release coming right up, right?
I would preserve the history, even if it takes a small amount of extra time. There's a lot of value in being able to read through commit logs and understand why function X is written in a weird way, or that this really is an off-by-one error because it was written by Oliver, who always gets that wrong.
The argument against preserving the history can be made for the following users:
your code might have embarrassing things, like profanity and fighting among developers
you don't care about the commit history of your code, because it's not going to change or be maintained in the future
I did some directory refactoring like this last year on our code base. If your code is reasonable structured at the beginning, you can do about 75-90% of the work using scripts written in your language of choice (I used Perl). In my case, we were moving from set of files all in one big directory, to a series of nested directories depending on namespaces. So, a file that declared the class protocols::serialization::SerializerBase was located in src/protocols/serialization/SerializerBase. The mapping from the old name to the new name was trivial, so that doing a find and replace on #includes in every source file in the tree was trivial, although it was a big change. There were a couple of weird edge cases that we had to fix by hand, but that seemed a lot better than either having to do everything by hand or having to write our own C++ parser.
Hacking up a shell script to do the svn moves is trivial. In tcsh it's foreach F ( $FILES ) ... end to adjust a set of files. Perl & Python offer better utility.
It really is worth saving the history. Especially when trying to track down some exotic bug. Those who do not learn from history are doomed to repeat it, or some such junk...
As for altering all the files... There was a similar question just the other day over at:
https://stackoverflow.com/questions/573430/
c-include-header-path-change-windows-to-linux/573531#573531