implementing .cpp and .h files

closed account (SwXE8vqX)
Hi everyone, I'm fairly new to c++ programming and I was just experimenting with this program, that works out symbol frequency, and I was wondering how I would turn this .cpp file, into a .cpp file and a .h file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  #include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <cstddef>
using namespace std;

int main()
{
    string Frequency;                     
    ifstream infile; 
    int i = 0;                              
    infile.open("richardiii.txt");        
    getline(infile,Frequency);            
    infile.close();                         
{
	
    std::map<char, std::size_t> freq;
    for(auto c: Frequency)
    {
        if( freq.find(c) == freq.end())
            freq[c] = 1; 
        else
            ++freq[c];
    }

    for(auto elem: freq)
    {
        std::cout << elem.first << " -> " << elem.second << std::endl;
    }
}
}


Thanks
Last edited on
closed account (EwCjE3v7)
Well if you would like all your work in the .h file, make a function there and put your work in there.

There you can include that file in your .cpp file and call that function.

It's also good practice if you define preprocessor directives, what this does is that if the code is already defined, then do not redefine it. This is separate to the actual program.

test.h file:

1
2
3
4
5
6
7
8
9
10
11
12
13

#ifndef test_h  //check not already defined
#define test_h	 //if not, define

#include <string>

std::string foo()
{
    std::string s = "Hello";
    s += " World!";
    return s;
}
#endif  // test_h 


test.cpp file:

1
2
3
4
5
6
7
8
#include <iostream>
#include "test.h"

int main()
{
    std::cout << foo() << std::endl;
    return 0;
}
Last edited on
don't put function definitions in header files (unless they are inline or template)
it will cause "multiple definition" errors at linking time
Last edited on
Topic archived. No new replies allowed.