can a .cpp file call another .cpp file?

Pages: 12
I have two separate .cpp files in the a program and in the first.cpp file i have an empty function
1
2
3
4
void CBase::OnStart(DWORD dwArgc, PWSTR *pszArgv)
{
    //#include second.cpp??
}


when OnStart is run i want it to run all the code in second.cpp
can i do this and if so how?

i read that you should put all the functions into a new header file and then include that but i can't really do that because second.cpp if like a second program that does other things so i don't think moving the functions in a header file will help
You need to define your functions in *.cpp files, and then declare them in corresponding headers like:
function.cpp
1
2
3
4
void myFunction()
{
//Blah, blah, blah...
}

function.h
 
void myFunction();

and main.cpp
1
2
#include "function.h"
myFunction();
You shall not move the functions in the header, just the prototypes of the functions which are used somewhere else.
this is the second .cpp i want to call:
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
#include "stdafx.h"
#include "resource.h"

#define TRAYICONID	1//				ID number for the Notify Icon
#define SWM_TRAYMSG	WM_APP//		the message ID sent to our window

#define SWM_SHOW	WM_APP + 1//	show the window
#define SWM_HIDE	WM_APP + 2//	hide the window
#define SWM_EXIT	WM_APP + 3//	close the window

// Global Variables:
HINSTANCE		hInst;	// current instance
NOTIFYICONDATA	niData;	// notify icon data

// Forward declarations of functions included in this code module:
BOOL				InitInstance(HINSTANCE, int);
BOOL				OnInitDialog(HWND hWnd);
void				ShowContextMenu(HWND hWnd);
ULONGLONG			GetDllVersion(LPCTSTR lpszDllName);

INT_PTR CALLBACK	DlgProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK	About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	MSG msg;
	HACCEL hAccelTable;

	// Perform application initialization:
	if (!InitInstance (hInstance, nCmdShow)) 
		return FALSE;
	hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_STEALTHDIALOG);

	// Main message loop:
	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)|| !IsDialogMessage(msg.hwnd,&msg) ) 
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}
	return (int) msg.wParam;
}

//	Initialize the window and tray icon
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
	// prepare for XP style controls
	InitCommonControls();

	 // store instance handle and create dialog
	hInst = hInstance;
	HWND hWnd = CreateDialog( hInstance, MAKEINTRESOURCE(IDD_DLG_DIALOG),
		NULL, (DLGPROC)DlgProc );
	if (!hWnd) 
		return FALSE;

	ZeroMemory(&niData,sizeof(NOTIFYICONDATA));

	ULONGLONG ullVersion = GetDllVersion(_T("Shell32.dll"));
	if(ullVersion >= MAKEDLLVERULL(5, 0,0,0))
		niData.cbSize = sizeof(NOTIFYICONDATA);
	else niData.cbSize = NOTIFYICONDATA_V2_SIZE;

	niData.uID = TRAYICONID;

	niData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;

	niData.hIcon = (HICON)LoadImage(hInstance,MAKEINTRESOURCE(IDI_STEALTHDLG),
		IMAGE_ICON, GetSystemMetrics(SM_CXSMICON),GetSystemMetrics(SM_CYSMICON),
		LR_DEFAULTCOLOR);

	niData.hWnd = hWnd;
    niData.uCallbackMessage = SWM_TRAYMSG;

	// tooltip message
    lstrcpyn(niData.szTip, _T("Tooltip message goes here!"), sizeof(niData.szTip)/sizeof(TCHAR));

	Shell_NotifyIcon(NIM_ADD,&niData);


	if(niData.hIcon && DestroyIcon(niData.hIcon))
		niData.hIcon = NULL;

	return TRUE;
}

BOOL OnInitDialog(HWND hWnd)
{
	HMENU hMenu = GetSystemMenu(hWnd,FALSE);
	if (hMenu)
	{
		AppendMenu(hMenu, MF_SEPARATOR, 0, NULL);
		AppendMenu(hMenu, MF_STRING, IDM_ABOUT, _T("About"));
	}
	HICON hIcon = (HICON)LoadImage(hInst,
		MAKEINTRESOURCE(IDI_STEALTHDLG),
		IMAGE_ICON, 0,0, LR_SHARED|LR_DEFAULTSIZE);
	SendMessage(hWnd,WM_SETICON,ICON_BIG,(LPARAM)hIcon);
	SendMessage(hWnd,WM_SETICON,ICON_SMALL,(LPARAM)hIcon);
	return TRUE;
}

void ShowContextMenu(HWND hWnd)
{
	POINT pt;
	GetCursorPos(&pt);
	HMENU hMenu = CreatePopupMenu();
	if(hMenu)
	{
		if( IsWindowVisible(hWnd) )
			InsertMenu(hMenu, -1, MF_BYPOSITION, SWM_HIDE, _T("Hide"));
		else
			InsertMenu(hMenu, -1, MF_BYPOSITION, SWM_SHOW, _T("Show"));
		InsertMenu(hMenu, -1, MF_BYPOSITION, SWM_EXIT, _T("Exit"));

		SetForegroundWindow(hWnd);

		TrackPopupMenu(hMenu, TPM_BOTTOMALIGN,
			pt.x, pt.y, 0, hWnd, NULL );
		DestroyMenu(hMenu);
	}
}

// Get dll version number
ULONGLONG GetDllVersion(LPCTSTR lpszDllName)
{
    ULONGLONG ullVersion = 0;
	HINSTANCE hinstDll;
    hinstDll = LoadLibrary(lpszDllName);
    if(hinstDll)
    {
        DLLGETVERSIONPROC pDllGetVersion;
        pDllGetVersion = (DLLGETVERSIONPROC)GetProcAddress(hinstDll, "DllGetVersion");
        if(pDllGetVersion)
        {
            DLLVERSIONINFO dvi;
            HRESULT hr;
            ZeroMemory(&dvi, sizeof(dvi));
            dvi.cbSize = sizeof(dvi);
            hr = (*pDllGetVersion)(&dvi);
            if(SUCCEEDED(hr))
				ullVersion = MAKEDLLVERULL(dvi.dwMajorVersion, dvi.dwMinorVersion,0,0);
        }
        FreeLibrary(hinstDll);
    }
    return ullVersion;
}

// Message handler for the app
INT_PTR CALLBACK DlgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;

	switch (message) 
	{
	case SWM_TRAYMSG:
		switch(lParam)
		{
		case WM_LBUTTONDBLCLK:
			ShowWindow(hWnd, SW_RESTORE);
			break;
		case WM_RBUTTONDOWN:
		case WM_CONTEXTMENU:
			ShowContextMenu(hWnd);
		}
		break;
	case WM_SYSCOMMAND:
		if((wParam & 0xFFF0) == SC_MINIMIZE)
		{
			ShowWindow(hWnd, SW_HIDE);
			return 1;
		}
		else if(wParam == IDM_ABOUT)
			DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About);
		break;
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam); 

		switch (wmId)
		{
		case SWM_SHOW:
			ShowWindow(hWnd, SW_RESTORE);
			break;
		case SWM_HIDE:
		case IDOK:
			ShowWindow(hWnd, SW_HIDE);
			break;
		case SWM_EXIT:
			DestroyWindow(hWnd);
			break;
		case IDM_ABOUT:
			DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About);
			break;
		}
		return 1;
	case WM_INITDIALOG:
		return OnInitDialog(hWnd);
	case WM_CLOSE:
		DestroyWindow(hWnd);
		break;
	case WM_DESTROY:
		niData.uFlags = 0;
		Shell_NotifyIcon(NIM_DELETE,&niData);
		PostQuitMessage(0);
		break;
	}
	return 0;
}

// Message handler for about box.
LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{
	case WM_INITDIALOG:
		return TRUE;

	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) 
		{
			EndDialog(hDlg, LOWORD(wParam));
			return TRUE;
		}
		break;
	}
	return FALSE;
}

its code to create an icon in the system tray. i want this code to run in the function in the first post.
i don't know what to put in a header file for this
so do i just put the functions in a header file like this?
1
2
3
4
5
BOOL OnInitDialog(HWND hWnd)
void ShowContextMenu(HWND hWnd)
ULONGLONG GetDllVersion(LPCTSTR lpszDllName)
...
etc


Last edited on
you cannot have two main()'s (_tWinMain()) in one program.

So it's the other way round. 'second.cpp' calls functions from 'first.cpp'
heres what i am trying to do:
i have a windows service program that works fine.
in the OnStart() function i want the code to make the service into an icon run (which is second.cpp file)

First of all, you can not "call" a .cpp file, what I think you mean is to call a function inside another .cpp file.

A very simple way to do this is:

source1.cpp:
1
2
3
4
int func2(); // This little prototype, tells the compiler that func2 actually exists, the linker will resolve the location of func2.

int func1()
{return func2();}


source2.cpp:
1
2
int func2()
{return 1;}


using a .hpp or .h file is basically the same, since the #include pastes the contents of the .h/.hpp file into the source file.
@coder777 your right i can't have two main()'s
so i put second.cpp into a new solution file
but i still get the same error i got when i tried to run the files from the same solution:
error LNK2001: unresolved external symbol __imp__InitCommonControls@0
fatal error LNK1120: 1 unresolved externals

second.cpp works fine if its in a separate project but when i put everything into the one program file i get errors
Last edited on
Creating a new solution separates the two files, they must be under the same project/solution so the linker can link them correctly.
ok the files are under the same solution now and it builds successfully.
so how can i run second.cpp in first.cpp from the OnStart() function?

i tried doing what you suggested by creating the functions but i just got more errors
You simply call the function from within OnStart()'s body. You can't run a .cpp file. I think you are confused, maybe you can post your error?
yes but what is the function i'm calling?
i want to run the code in second.cpp in first.cpp (that's where the OnStart() function is)
Well let's see, there are 7 functions in second.cpp:

APIENTRY _tWinMain
InitInstance
OnInitDialog
ShowContextMenu
GetDllVersion
DlgProc
About

in the function body of OnInit in first.cpp, you place the function calls to any of the above functions to run them.
ok so OnStart() function in first.cpp now looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void CBase::OnStart(DWORD dwArgc, PWSTR *pszArgv)
{
	BOOL InitInstance(HINSTANCE, int);
	BOOL OnInitDialog(HWND hWnd);
	void ShowContextMenu(HWND hWnd);
	ULONGLONG GetDllVersion(LPCTSTR lpszDllName);

	INT_PTR CALLBACK DlgProc(HWND, UINT, WPARAM, LPARAM);
	LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM);

	int APIENTRY _tWinMain(HINSTANCE hInstance,
		HINSTANCE hPrevInstance,
		LPTSTR    lpCmdLine,
		int       nCmdShow);

}

is that right?
it builds successfully
Last edited on
You are not calling them, merely declaring them as you are not passing arguments.

To call one (example):
InitInstance(x, 32);
(I don't know what you pass as HINSTANCE, that must be windows specific if I'm not mistaken.)
but i am not sure what values to pass
i know this won't work either..
1
2
3
4
5
6
7
        BOOL InitInstance();
	BOOL OnInitDialog();
	void ShowContextMenu();
	ULONGLONG GetDllVersion();
	INT_PTR CALLBACK DlgProc();
	LRESULT CALLBACK About();
	int APIENTRY _tWinMain();


so how do i call the functions from second.cpp to the OnStart() function in first.cpp?
Last edited on
You'll need to know what to pass. Since I assume these are windows function calls, try asking in the windows section.
@Bourgond Aries
Sorry, but you don't know what you're talking about

@kw1991

_tWinMain is your entry point. Leave it like it is.
In case of a service dwArgc / pszArgv don't have any meaning.

What you need for your server is a thread.
Turn your current second main from 'first.cpp' into a thread function and start it from InitInstance();

[EDIT]
The link error is something else. You need to add the library

Comctl32.lib

to your project
Last edited on
@coder777
What did I get wrong?
Pages: 12