undefined reference to `TextOutA#20' [duplicate] - c++

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 5 years ago.
I am kind of stuck on this and would appreciate help in solving this please. I am using window GDI, and according to this link, including windows.h is what is needed to work with the TextOut function, among others, but I am still getting some undefined reference error messages and I am stuck.
**undefined reference to `TextOutA#20'|
undefined reference to `CreateDCA#16'|
undefined reference to `Escape#20'|
undefined reference to `DeleteDC#4'|**
#include <Windows.h>// HDC is a typedef defined in the windows.h library
#include <stdlib.h>
#include <stdio.h>
#include <fstream>
#include <strstream>
#include <string.h>
using namespace std;
#define IDM_QUIT 102
#define EXAMPLE 101
#define IDM_PRINT 27
#define IDM_SHOW 1
//this excerpt demonstrates how to get the handle to a device context ysing the BegingPaint() GDI function
long FAR PASCAL _export WINDOWPROCEDURE(HWND hwnd, UINT message, UINT wParam, LONG Param)
{
HDC hdc;
PAINTSTRUCT ps;
RECT area;
char PInfo[80]="";
char DriverName[20];
char DeviceName[40];
char Other[20];
int X,Y;
X=100;
Y=100;
switch(message)
{
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
TextOut(hdc,X,Y, "Speed of Light", 14);
EndPaint(hwnd, &ps);
case IDM_SHOW:
hdc = GetDC(hwnd);
TextOut(hdc, X,Y, "Speed of Light", 14);
ReleaseDC(hwnd, hdc);
case IDM_PRINT:
GetProfileString("windows", "device", "", PInfo,80);
istrstream In(PInfo);
In.getline(DeviceName, 80, ',');
In.getline(DriverName, 80, ',');
In.getline(Other,80, ',');
hdc = CreateDC(DriverName, DeviceName, Other, NULL);
Escape(hdc,
STARTDOC,8,
(LPSTR)"EXAMPLE",0L);
TextOut(hdc, X, Y, "Speed of Light", 14);
Escape(hdc, NEWFRAME, 0,0L, 0L);
Escape(hdc, ENDDOC, 0,0L, 0L);
DeleteDC(hdc);
}
return 0;
}

Linking to gdi32.lib should solve the problem. :)

Ohh friend,if you have faced this type of error in dev cpp,then go to tool->compliler option->
click on the settings tab ->linker->change dont create console window to "YES"->CLICK OK.Your problem may be solved.

Related

Print text and images in C++ (WinAPI or QT)

In a basic program, I need to know how to make a text display widget and image display that can both be changed to different strings and images on command. These will display on a basic GUI.
Any specific help would be tremendously appreciated as I have been stuck on this for more than 10 weeks! Asking online here is my last resort.
I am making a basic program that asks questions (which is my text I want to print) and images for the questions come up underneath it. I have successfully made this program in a console command window (the code I will share below) but this of course meant no images could be displayed, so I am having to remake it in a GUI that supports images.
This is my first project ever done in C++, and only know the basics (the full extent of my limited knowledge got me through making that console command window program without help).
I first used WinAPI as it came with my computer in microsoft visual studio, and tried many different suggestions by other's similar questions already answered, but always either had one of two problems; 1. The code they supplied had many errors of which most read "_ is undefined" or wasn't imported properly, or 2. created basic text successfully but didn't specify how to change it after it had been created (I have had no successful image prints so far). I have tried 3 question/answers from cplusplus.com and 3 from stack overflow (links will be below), and all of them have had these 2 problems that are created from my lack of C++ bug fixing skills.
Suggestions using WinAPI would be prefferred over QT as I have no idea what I am doing in Qt and get double digit numbers worth of errors when I import code (even though I import the correct directories), whereas WinAPI doesn't get importing errors.
Code for command console program:
//G-Learning
//#author: James Monk
//#completed: 7/6/16
//#version 1.0
//These are the libraries (external files) to include at the start.
#include <cstdio>
#include <windows.h>
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string>
using namespace std;
//Defining the [global] variables that will be used throughout the program
int running = 1;
int menuSelection;
int questionsLeft = 5;
int questionTextPicked;
int questionImagePicked;
int questionRandomised;
int score = 0;
int userInput;
int userInputDummy;
string stringPointer;
int intPointer;
string questionText[10] = {
"Would this most likely be, (1) an enemy (2) a player?\n",
"Is this (1) how many hearts the player has inside their body, or (2) a number of lives the player has?\n",
"Is this (1) a health bar, or (2) a set of red lights?\n",
"Is this (1) a money counter, or (2) a yellow ball counter?\n",
"Would this be a good object to touch with your character? (1) no or (2) yes?\n",
"What would this object likely have in it? (1) rewards, or (2) punishments\n",
"What does 'Game Over' mean? (1) your session has ended, or (2) the game is no longer playable\n",
"What would an icon like this likely be for? (1) show wheels, or (2) options\n",
"In a racing game, what would this be for? (1) health bar, or (2) fuel tank meter\n",
"What would this button likely do? (1) exit or cancel, or (2) mark a spot with an x\n" };
//Defining what happens with the different functions
void introduction() {
printf("\nG-Learning is a program built to teach people who know little about games the basic features of them. \n\n\
Questions will be asked, and you will need to answer them by choosing the correct answer.\n\
You will need to press 1, 2, or 3 followed by enter to choose.\n\n\
Press any number key followed by enter to return to the main menu.\n\n");
cin >> userInputDummy;
menuSelection = 0;
}
void start() {
printf("\nThe questions will now start, good luck!\n\n");
while (questionsLeft > 0) {
questionTextPicked = (rand() % 10);
if (questionTextPicked == 0) {
questionRandomised = (rand() % 4);
questionImagePicked = (7 + questionRandomised);
}
else if (questionTextPicked == 4) {
questionRandomised = (rand() % 3);
questionImagePicked = (11 + questionRandomised);
}
else {
questionImagePicked = questionTextPicked;
}
printf("after calculations, questionTextPicked is %d, questionRandomised is %d, and questionImagePicked is %d\n\n", questionTextPicked, questionRandomised, questionImagePicked);
//answering questions should be here
stringPointer = questionText[questionTextPicked];
intPointer = questionAnswer[questionImagePicked];
printf("answer is %d\n\n", intPointer);
printf("%s\n", stringPointer, intPointer);
printf("answer is %d\n\n", intPointer);
cin >> userInput;
if (userInput == questionAnswer[questionImagePicked]) {
printf("\nCorrect!\n\n");
score++;
}
else {
printf("\nIncorrect answer.\n\n");
}
questionsLeft--;
if (questionsLeft > 0) {
printf("%d questions to go!\n\n", questionsLeft);
}
if (questionsLeft == 0) {
printf("All questions have been answered, you scored %d/5.\n\nReturning you to the main menu\n\n", score);
score = 0;
}
} //end of start's while loop
menuSelection = 0;
} //end of start's function
void exit() {
menuSelection = 0;
running = 0;
}
//||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
//Main function, where everything starts
int main(int argc, char ** argv) {
while (running == 1) {
//Welcoming the user to the program, and asking them what they want to do (starts functions)
printf("welcome to G-Learning! Press a key to get started.\n1: Instructions\n2: Start\n3: Exit\n\n");
questionsLeft = 5; //Resetting this so that the start function can begin again
cin >> menuSelection;
if (menuSelection == 1) {
introduction();
}
else if (menuSelection == 2) {
start();
}
else if (menuSelection == 3) {
exit();
}
else {
printf("Invalid input, please use the 1, 2, or 3 key.");
}
}
return 0;
return EXIT_SUCCESS;
} //end of main function
Code for my best working WinAPI iteration (can print text, but not again on command; also without image functionality. Would like to know how to improve this one!):
//These are the libraries (external files) to include at the start.
#include <cstdio>
#include <windows.h>
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string>
using namespace std;
int textHorizontal = 10;
int textVertical = 10;
//Variables used in making the program window
int numberInput;
char charictorInput;
string stringInput;
const char g_szClassName[] = "myWindowClass";
HINSTANCE hInstance;
// Function to get the size of the text
int GetTextSize(LPSTR a0)
{
for (int iLoopCounter = 0; ; iLoopCounter++)
{
if (a0[iLoopCounter] == '\0')
return iLoopCounter;
}
}
LPSTR TextArray[] = {
"Hello World"
};
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
TextOut(hdc,
// Location of the text
textHorizontal,
textVertical,
// Text to print
TextArray[0],
// Size of the text, my function gets this for us
GetTextSize(TextArray[0]));
EndPaint(hwnd, &ps);
}
break;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
int WINAPI WinMain(HINSTANCE hInstanace, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX WindowClass;
WindowClass.cbClsExtra = 0;
WindowClass.cbWndExtra = 0;
WindowClass.cbSize = sizeof(WNDCLASSEX);
WindowClass.lpszClassName = "1";
WindowClass.lpszMenuName = NULL;
WindowClass.lpfnWndProc = WndProc;
WindowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
WindowClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
WindowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
WindowClass.style = 0;
WindowClass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
RegisterClassEx(&WindowClass);
HWND hwnd = CreateWindowEx(WS_EX_CLIENTEDGE,
"1",
"G-Learning by James Monk",
WS_OVERLAPPEDWINDOW,
315, 115,
1080, 720,
NULL,
NULL,
hInstance,
NULL);
ShowWindow(hwnd, SW_SHOWNORMAL);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if (VK_ESCAPE == msg.wParam)
break;
}
return 0;
}
I am limited to only 2 links, so to view the 3 cplusplus.com pages I tried and the 3 stack overflow pages I tried, the links to them are on a google document here:
https://docs.google.com/document/d/1IX2hxzAVka3UmVkaAgv-gXv_cwwmP3FkTYQuFWrrqyE/edit?usp=sharing
How I installed QT into Microsoft Visual Studio:
https://www.youtube.com/watch?v=P6Mg8FpFPS8
Thank you for reading through my issue and even more in advance for helping!
HINSTANCE hInstance;
int WINAPI WinMain(HINSTANCE hInstanace...
CreateWindowEx(... hInstance ...)
You have spelling errors here. hInstanace and hInstance are not the same. Visual Studio should give you warnings. Set the warning level to 4. Address all the warnings and fix them. Only in rare cases is it okay to ignore warnings.
Moreover, in declaration of WNDCLASSEX WindowClass; you missed initializing hInstance, so the code will go nowhere. In C++ 14 you can do this
WNDCLASSEX WindowClass = {0}
This will initialize all members to zero. Try to always do this when declaring data on stack. Also avoid putting random code in to message loop.
#include <cstdio>
#include <iostream>
#include <windows.h>
Above header files are for C input/output, C++ input/output, and WinAPI. Usually you don't need them all. Pick one.
LPSTR TextArray[] = {
"Hello World"
};
Above is a character array, or just "text". If you access TextArray[0] it gives you the character 'H'
int GetTextSize(LPSTR a0)
{
for (int iLoopCounter = 0; ; iLoopCounter++)
{
if (a0[iLoopCounter] == '\0')
return iLoopCounter;
}
}
Above code is the equivalent of strlen. Your code is all over the place. You have C++14 classes like std::string, C header files, useless functions like GetTextSize which is mostly for learning C/C++, more advanced WinAPI, and some mention of Qt cross development. I recommend you spend more time with a C++ book. Here is example of what you are trying to do:
#include <windows.h>
#include <string>
#include <vector>
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
static HWND combobox;
static std::vector<std::string> vec = {
"Would this most likely be, (1) an enemy (2) a player?\n",
"Is this (1) how many hearts the player has inside their body, or (2) a number of lives the player has?\n",
"Is this (1) a health bar, or (2) a set of red lights?\n",
"Is this (1) a money counter, or (2) a yellow ball counter?\n",
"Would this be a good object to touch with your character? (1) no or (2) yes?\n",
"What would this object likely have in it? (1) rewards, or (2) punishments\n",
"What does 'Game Over' mean? (1) your session has ended, or (2) the game is no longer playable\n",
"What would an icon like this likely be for? (1) show wheels, or (2) options\n",
"In a racing game, what would this be for? (1) health bar, or (2) fuel tank meter\n",
"What would this button likely do? (1) exit or cancel, or (2) mark a spot with an x\n"
};
switch (msg)
{
case WM_CREATE:
combobox = CreateWindow("ComboBox", 0, CBS_DROPDOWNLIST | CBS_HASSTRINGS | WS_CHILD | WS_OVERLAPPED | WS_VISIBLE, 0, 100, 700, 30, hwnd, HMENU(100), 0, 0);
for (auto line : vec) SendMessage(combobox, CB_ADDSTRING, 0, LPARAM(line.c_str()));
break;
case WM_KEYDOWN:
if (wParam == VK_ESCAPE)
DestroyWindow(hwnd);
break;
case WM_COMMAND:
if (HIWORD(wParam) == CBN_SELCHANGE)
InvalidateRect(hwnd, NULL, TRUE);
break;
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
int sel = SendMessage(combobox, CB_GETCURSEL, 0, 0);
if (sel < 0) sel = 0;
TextOut(hdc, 0, 0, vec[sel].c_str(), vec[sel].size());
EndPaint(hwnd, &ps);
break;
}
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX wcx = { 0 };
wcx.cbSize = sizeof(WNDCLASSEX);
wcx.lpszClassName = "ClassName";
wcx.lpfnWndProc = WndProc;
wcx.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcx.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
wcx.hCursor = LoadCursor(NULL, IDC_ARROW);
wcx.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
RegisterClassEx(&wcx);
HWND hwnd = CreateWindowEx(0, wcx.lpszClassName, "G-Learning by James Monk", WS_VISIBLE|WS_OVERLAPPEDWINDOW, 0,0,800,600, NULL, NULL, hInstance, NULL);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}

It is possible to declare string[] with a specific name? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm studying the string type, and I stumbled across char string[]. Its confusing and I don't even know what it is. Its strange that i can't declare a string after I use it, because its using like a variable and it doesn't allow me to declare other strings. So how to add a name to that char array? Here is the code so I hope its understandable what I mean. Thanks.
#include "iostream"
#include "string.h"
using namespace std;
int main(){
char string[] = "hello stackoverflow";
string word("hello stackoverflow"); //cant declare "word"
//because i declare it above, and i want to know how to avoid that..
cout<<word;
cout<<string;
}
the code I'm studying is this:
/* Trim fat from windows*/
#define WIN32_LEAN_AND_MEAN
#pragma comment(linker, "/subsystem:windows")
/* Pre-processor directives*/
#include <windows.h>
#include "string.h"
/* Windows Procedure Event Handler*/
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT paintStruct;
/* Device Context*/
HDC hDC;
/* Text for display*/
char string [] = "hi im a form"; //this is whats i don't understand what //it is
/* Switch message, condition that is met will execute*/
switch(message)
{
/* Window is being created*/
case WM_CREATE:
return 0;
break;
/* Window is closing*/
case WM_CLOSE:
PostQuitMessage('0');
return 0;
break;
/* Window needs update*/
case WM_PAINT:
hDC = BeginPaint(hwnd,&paintStruct);
/* Set txt color to blue*/
SetTextColor(hDC, COLORREF(0xffff1a));
/* Display text in middle of window*/
TextOut(hDC,150,150,string,sizeof(string)-1); //and here why its //only able to declare it as "string" and not as a name
EndPaint(hwnd, &paintStruct);
return 0;
break;
default:
break;
}
return (DefWindowProc(hwnd,message,wParam,lParam));
}
char c_str[] = "hello";
This declares a variable named c_str of type char [6] a.k.a static array of 6 chars initialized with "hello";
std::string cpp_string("hello");
This declares a variable named cpp_string of type std::string initialized with "hello". If you add using namespace std;, then you can use string instead of std::string.
All declarations of a variable must have the same type. You cannot define a variable multiple times.
You should not declare a variable with the same name as a type.

tcc: error: undefined symbol '_GetConsoleWindow#0'

I'm making a program in C/C++ which must run hidden using this code:
#define _WIN32_WINNT 0x0500
#include <windows.h>
int main(){
HWND hWnd = GetConsoleWindow();
ShowWindow(hWnd, SW_HIDE);
. . .
}
I really want to use tinyc to compile it because it's much better than gcc (almost, the final executable is much tiny than gcc).
The point is that when I try to compile it using:
tcc PROGRAM.c -luser32
It makes an error which says:
tcc: error: undefined symbol '_GetConsoleWindow#0'
But when I use gcc it works! I think I have a missed library but I don't know which one.
Please, some help :)
According to MSDN, GetConsoleWindow is located in Kernel32.dll
Try:
tcc PROGRAM.c -luser32 -lkernel32
EDIT:
tcc's kernel32.def is missing the export for GetConsoleWindow.
Append the string GetConsoleWindow at the end of the def file located in the lib directory inside tcc's installation folder.
remove gdi32.def kernel32.def msvcrt.def user32.def files from C:\tcc\lib; remove all .def files from C:\tcc\lib
#include <windows.h>
#include <wincon.h>
#include <stdio.h>
#include <conio.h>
void main()
{
HWND hwnd;
hwnd = GetConsoleWindow();
HDC hdc;
hdc = GetWindowDC(hwnd);
printf("console hwnd: %p\n", hwnd);
printf("console hdc: %p\n", hdc);
HPEN hPenNull, hPenBlack, hPenRed, hPenGreen, hPenBlue;
hPenNull=GetStockObject(NULL_PEN);
hPenBlack=CreatePen(PS_SOLID, 2, RGB(0,0,0));
hPenRed=CreatePen(PS_SOLID, 2, RGB(255,0,0));
hPenGreen=CreatePen(PS_SOLID, 2, RGB(0,255,0));
hPenBlue=CreatePen(PS_SOLID, 2, RGB(0,0,255));
HBRUSH hBrushNull, hBrushBlack, hBrushRed, hBrushGreen, hBrushBlue, hBrushYellow;
hBrushNull=GetStockObject(NULL_BRUSH);
hBrushBlack=CreateSolidBrush(RGB(0,0,0));
hBrushRed=CreateSolidBrush(RGB(255,0,0));
hBrushYellow=CreateSolidBrush(RGB(255,255,0));
hBrushGreen=CreateSolidBrush(RGB(0,255,0));
hBrushBlue=CreateSolidBrush(RGB(0,0,255));
SelectObject(hdc, hPenRed);
SelectObject(hdc, hBrushYellow);
Ellipse(hdc, 200,50,260,150);
SelectObject(hdc, hPenNull);
SelectObject(hdc, hBrushRed);
Ellipse(hdc, 140, 80, 180, 120);
SelectObject(hdc, hPenBlue);
SelectObject(hdc, hBrushNull);
Ellipse(hdc, 280, 50, 340, 150);
getch();
}
-L"C:\tcc\lib" -lkernel32 -luser32 -lgdi32 -Wl,-subsystem=console

Multiple monitors and handles

Trying to run a for loop through physical monitors but the handles are really confusing me, I have pseudo code that runs along the lines of:
int tempCounter=0
for(counter = number of monitors;counter > 0;counter--){
RECT tempRECT;
HDC tempHDC;
Get resolution of DC handle (counter) -> tempRECT;
arrayList[tempCounter] = tempRECT;
Get virtual work area of DC handle (counter) -> tempRECT;
arrayList[tempCounter++] = tempRECT;
tempCounter++;
}
GetSystemMetrics(80) for the count of monitors, is this reliable enough to use, or any exceptions it might fail?
I know there is not much there, but looking on the MSDN just kept me going around in circles, that and I am not very competent at programming.
It can be as simple as this:
#include <Windows.h>
#include <stdio.h>
BOOL CALLBACK MonitorEnumProc(
HMONITOR hMonitor,
HDC hdcMonitor,
LPRECT lprcMonitor,
LPARAM dwData
)
{
printf("%dx%d\n", lprcMonitor->right, lprcMonitor->bottom);
}
int main(int argc, char*argv[]) {
EnumDisplayMonitors(NULL, NULL, MonitorEnumProc, 0);
}

C++ Pixels In Console Window

In C++ using Code::Blocks v10.05, how do I draw a single pixel on the console screen? Is this easy at all, or would it be easier to just draw a rectangle? How do I color it?
I'm sorry, but I just can't get any code from SOF, HF, or even cplusplus.com to work. This is for a Super Mario World figure on the screen. The game I think is 16-bit, and is for the SNES system. C::B says I need SDK for C::B. It says "afxwin.h" doesn't exist. Download maybe?
This is what I'm trying to make:
It depends on your OS. I suppose you are programming in a Windows platform, therefore you can use SetPixel but you have to use "windows.h" to get a console handle, so here an example for drawing the cos() function:
#include<windows.h>
#include<iostream>
#include <cmath>
using namespace std;
#define PI 3.14
int main()
{
//Get a console handle
HWND myconsole = GetConsoleWindow();
//Get a handle to device context
HDC mydc = GetDC(myconsole);
int pixel =0;
//Choose any color
COLORREF COLOR= RGB(255,255,255);
//Draw pixels
for(double i = 0; i < PI * 4; i += 0.05)
{
SetPixel(mydc,pixel,(int)(50+25*cos(i)),COLOR);
pixel+=1;
}
ReleaseDC(myconsole, mydc);
cin.ignore();
return 0;
}
You can also use some others libraries like: conio.h allegro.h sdl, etc.
If you're willing to have the image look blocky, you could take advantage of the block characters from the console code page.
█ = '\xDB' = U+2588 FULL BLOCK
▄ = '\xDC' = U+2584 LOWER HALF BLOCK
▀ = '\xDF' = U+2580 UPPER HALF BLOCK
and space
By using the half-blocks in combination with colored text, you can turn an 80×25 console window into an 80×50 16-color display. (This was the approach used by the QBasic version of Nibbles.)
Then, you just need to convert your image to the 16-color palette and a reasonably small size.
windows.h provides a function SetPixel() to print a pixel at specified location of a window. The general form of the function is
SetPixel(HDC hdc, int x, int y, COLORREF& color);
where, x and y are coordinates of pixel to be display and color is the color of pixel.
Important: to print the pixel in your machine with Code::blocks IDE, add a link library libgdi32.a (it is usually inside MinGW\lib ) in linker setting.
Console is a text device, so in general you don't write to individual pixels. You can create a special font and select it as a font for console, but it will be monochromatic. There are libraries which simplify writing console UI (e.g. Curses), but I believe that you also have more gamelike functionality in mind besides just showing a sprite.
if you want to write a game, I suggest taking a look at some of the graphics/game frameworks/libs, e.g. SDL
I have drawn the straight line using windows.h in code::blocks. I can't explain it in details, but I can provide you a code and procedure to compile it in code::blocks.
go to setting menu and select compiler and debugger.
Click on linker tab and add a link library libgdi32.a which is at C:\Program Files\CodeBlocks\MinGW\lib directory.
Now compile this program
#include <windows.h>
#include <cmath>
#define ROUND(a) ((int) (a + 0.5))
/* set window handle */
static HWND sHwnd;
static COLORREF redColor=RGB(255,0,0);
static COLORREF blueColor=RGB(0,0,255);
static COLORREF greenColor=RGB(0,255,0);
void SetWindowHandle(HWND hwnd){
sHwnd=hwnd;
}
/* SetPixel */
void setPixel(int x,int y,COLORREF& color=redColor){
if(sHwnd==NULL){
MessageBox(NULL,"sHwnd was not initialized !","Error",MB_OK|MB_ICONERROR);
exit(0);
}
HDC hdc=GetDC(sHwnd);
SetPixel(hdc,x,y,color);
ReleaseDC(sHwnd,hdc);
return;
// NEVERREACH //
}
void drawLineDDA(int xa, int ya, int xb, int yb){
int dx = xb - xa, dy = yb - ya, steps, k;
float xIncrement, yIncrement, x = xa, y = ya;
if(abs(dx) > abs(dy)) steps = abs(dx);
else steps = abs(dy);
xIncrement = dx / (float) steps;
yIncrement = dy / (float) steps;
setPixel(ROUND(x), ROUND(y));
for(int k = 0; k < steps; k++){
x += xIncrement;
y += yIncrement;
setPixel(x, y);
}
}
/* Window Procedure WndProc */
LRESULT CALLBACK WndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam){
switch(message){
case WM_PAINT:
SetWindowHandle(hwnd);
drawLineDDA(10, 20, 250, 300);
break;
case WM_CLOSE: // FAIL THROUGH to call DefWindowProc
break;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
break; // FAIL to call DefWindowProc //
}
return DefWindowProc(hwnd,message,wParam,lParam);
}
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int iCmdShow){
static TCHAR szAppName[] = TEXT("Straight Line");
WNDCLASS wndclass;
wndclass.style = CS_HREDRAW|CS_VREDRAW ;
wndclass.lpfnWndProc = WndProc ;
wndclass.cbClsExtra = 0 ;
wndclass.cbWndExtra = 0 ;
wndclass.hInstance = hInstance ;
wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION) ;
wndclass.hCursor = LoadCursor (NULL, IDC_ARROW) ;
wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
wndclass.lpszMenuName = NULL ;
wndclass.lpszClassName = szAppName ;
// Register the window //
if(!RegisterClass(&wndclass)){
MessageBox(NULL,"Registering the class failled","Error",MB_OK|MB_ICONERROR);
exit(0);
}
// CreateWindow //
HWND hwnd=CreateWindow(szAppName,"DDA - Programming Techniques",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
hInstance,
NULL);
if(!hwnd){
MessageBox(NULL,"Window Creation Failed!","Error",MB_OK);
exit(0);
}
// ShowWindow and UpdateWindow //
ShowWindow(hwnd,iCmdShow);
UpdateWindow(hwnd);
// Message Loop //
MSG msg;
while(GetMessage(&msg,NULL,0,0)){
TranslateMessage(&msg);
DispatchMessage(&msg);
}
/* return no error to the operating system */
return 0;
}
In this program I have used DDA line drawing algorithm. Pixel drawing tasks is done by setPixel(ROUND(x), ROUND(y)) function.
This is windows programing which you can learn details here
To use in CodeBlocks I found this (you have to add a linker option -lgdi32):
//Code Blocks: Project Build Options Linker settings Othoer linker options: add -lgdi32
I forgot: You have to put this before including windows.h:
#define _WIN32_WINNT 0x0500
The whole cosine code again. Ready to compile:
//Code Blocks: Project Build Options Linker settings Othoer linker options: add -lgdi32
#define _WIN32_WINNT 0x0500
#include "windows.h"
#include <iostream>
#include <cmath>
using namespace std;
#define PI 3.14
int main(){
HWND myconsole = GetConsoleWindow();
HDC mydc = GetDC(myconsole);
int pixel =0;
COLORREF COLOR= RGB(255,255,255);
//Draw pixels
for(double i = 0; i < PI * 4; i += 0.05)
{
SetPixel(mydc,pixel,(int)(50+25*cos(i)),COLOR);
pixel+=1;
}
ReleaseDC(myconsole, mydc);
cin.ignore();
return 0;
}