Przykłady edytuj

Przykładowy program w C++:


Hello world edytuj

#include <iostream> 

int main () {

std::cout << "Hello, world!\n";

return 0;

}

Zapisujemy jako hello.cpp

Kompilujemy:

g++ -Wall hello.cpp

i uruchomiamy:

./a.out

ustawienia kompilatora edytuj

g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure 
-v 
--with-pkgversion='Ubuntu 11.4.0-1ubuntu1~22.04' 
--with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs 
--enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,m2 
--prefix=/usr 
--with-gcc-major-version-only 
--program-suffix=-11 
--program-prefix=x86_64-linux-gnu- 
--enable-shared 
--enable-linker-build-id 
--libexecdir=/usr/lib 
--without-included-gettext 
--enable-threads=posix 
--libdir=/usr/lib 
--enable-nls 
--enable-bootstrap 
--enable-clocale=gnu 
--enable-libstdcxx-debug 
--enable-libstdcxx-time=yes 
--with-default-libstdcxx-abi=new 
--enable-gnu-unique-object 
--disable-vtable-verify 
--enable-plugin 
--enable-default-pie 
--with-system-zlib 
--enable-libphobos-checking=release 
--with-target-system-zlib=auto 
--enable-objc-gc=auto 
--enable-multiarch 
--disable-werror 
--enable-cet 
--with-arch-32=i686 
--with-abi=m64 
--with-multilib-list=m32,m64,mx32 
--enable-multilib 
--with-tune=generic 
--enable-offload-targets=nvptx-none=/build/gcc-11-XeT9lY/gcc-11-11.4.0/debian/tmp-nvptx/usr,amdgcn-amdhsa=/build/gcc-11-XeT9lY/gcc-11-11.4.0/debian/tmp-gcn/usr 
--without-cuda-driver 
--enable-checking=release 
--build=x86_64-linux-gnu 
--host=x86_64-linux-gnu 
--target=x86_64-linux-gnu 
--with-build-config=bootstrap-lto-lean 
--enable-link-serialization=2
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04)


Funkcje C++20 są dostępne od wersji GCC 8. Aby włączyć obsługę C++20, dodaj parametr wiersza poleceń:[1]

-std=c++20

Biblioteki edytuj


bitowe edytuj

  • bitmanip Single-header C++ library for bit manipulation.

geometryczne edytuj

graficzne edytuj


OpenGl edytuj

sdl2 edytuj

 
// code nicked mainly from here:
// http://lazyfoo.net/tutorials/SDL/50_SDL_and_opengl_2/index.php


/* to compile

    ### installation on ubuntu
    # install compiler etc
    sudo apt-get install --yes software-properties-common g++ make
    # install sdl2
    sudo apt-get install --yes libsdl2-dev
    # install opengl
    sudo apt-get install --yes freeglut3-dev

    # compile with
    g++ main.cpp -I /usr/include/SDL2/ -lSDL2  -lGL
    g++ s.cpp -I{/include} -L{/lib} -Wall -lSDL2main -lSDL2  -lGL
    
    
    ## installation on mac
    # install xcode with command line tools
    # install sdl2*.dmg, put everything in ~/Library/Frameworks

    # compile with with g++ (or with clang++)
    g++ main.cpp -I ~/Library/Frameworks/SDL2.framework/Headers -I OpenGL -framework SDL2  -F ~/Library/Frameworks -framework OpenGL





g++ s.cpp -I{Path to SDL2\include} -L{Path to SDL2\lib} -Wall -lmingw32 -lSDL2main -lSDL2 
g++ s.cpp -I{/include} -L{/lib} -Wall -lSDL2main -lSDL2  -lGL



#include <SDL.h>
#include <SDL_opengl.h>
*/
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include <stdio.h>


//Screen dimension constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;


//Main loop flag
bool quit = false;


//Starts up SDL, creates window, and initializes OpenGL
bool init();

//Initializes matrices and clear color
bool initGL();

//Input handler
void handleKeys( unsigned char key, int x, int y );

//Per frame update
void update();

//Renders quad to the screen
void render();

//Frees media and shuts down SDL
void close();

//The window we'll be rendering to
SDL_Window* gWindow = NULL;

//OpenGL context
SDL_GLContext gContext;

//Render flag
bool gRenderQuad = true;

bool init()
{
    //Initialization flag
    bool success = true;

    //Initialize SDL
    if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() );
        success = false;
    }
    else
    {
        //Use OpenGL 2.1
        SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 2 );
        SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );

        //Create window
        gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN );
        if( gWindow == NULL )
        {
            printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() );
            success = false;
        }
        else
        {
            //Create context
            gContext = SDL_GL_CreateContext( gWindow );
            if( gContext == NULL )
            {
                printf( "OpenGL context could not be created! SDL Error: %s\n", SDL_GetError() );
                success = false;
            }
            else
            {
                //Use Vsync
                if( SDL_GL_SetSwapInterval( 1 ) < 0 )
                {
                    printf( "Warning: Unable to set VSync! SDL Error: %s\n", SDL_GetError() );
                }

                //Initialize OpenGL
                if( !initGL() )
                {
                    printf( "Unable to initialize OpenGL!\n" );
                    success = false;
                }
            }
        }
    }

    return success;
}

bool initGL()
{
    bool success = true;
    GLenum error = GL_NO_ERROR;

    //Initialize Projection Matrix
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    
    //Check for error
    error = glGetError();
    if( error != GL_NO_ERROR )
    {
        success = false;
    }

    //Initialize Modelview Matrix
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    //Check for error
    error = glGetError();
    if( error != GL_NO_ERROR )
    {
        success = false;
    }
    
    //Initialize clear color
    glClearColor( 0.f, 0.f, 0.f, 1.f );
    
    //Check for error
    error = glGetError();
    if( error != GL_NO_ERROR )
    {
        success = false;
    }
    
    return success;
}

void handleKeys( unsigned char key, int x, int y )
{
    if( key == 'q' )
    {
        quit = true;
    }
}

void update()
{
    //No per frame update needed
}

void render()
{
    //Clear color buffer
    glClear( GL_COLOR_BUFFER_BIT );
    
    //Render quad
    if( gRenderQuad )
    {
        glRotatef(0.4f,0.0f,1.0f,0.0f);    // Rotate The cube around the Y axis
        glRotatef(0.2f,1.0f,1.0f,1.0f);
        glColor3f(0.0f,1.0f,0.0f); 

        glBegin( GL_QUADS );
            glVertex2f( -0.5f, -0.5f );
            glVertex2f( 0.5f, -0.5f );
            glVertex2f( 0.5f, 0.5f );
            glVertex2f( -0.5f, 0.5f );
        glEnd();
    }
}

void close()
{
    //Destroy window    
    SDL_DestroyWindow( gWindow );
    gWindow = NULL;

    //Quit SDL subsystems
    SDL_Quit();
}

int main( int argc, char* args[] )
{
    //Start up SDL and create window
    if( !init() )
    {
        printf( "Failed to initialize!\n" );
    }
    else
    {

        //Event handler
        SDL_Event e;
        
        //Enable text input
        SDL_StartTextInput();

        //While application is running
        while( !quit )
        {
            //Handle events on queue
            while( SDL_PollEvent( &e ) != 0 )
            {
                //User requests quit
                if( e.type == SDL_QUIT )
                {
                    quit = true;
                }
                //Handle keypress with current mouse position
                else if( e.type == SDL_TEXTINPUT )
                {
                    int x = 0, y = 0;
                    SDL_GetMouseState( &x, &y );
                    handleKeys( e.text.text[ 0 ], x, y );
                }
            }

            //Render quad
            render();
            
            //Update screen
            SDL_GL_SwapWindow( gWindow );
        }
        
        //Disable text input
        SDL_StopTextInput();
    }

    //Free resources and close SDL
    close();

    return 0;
}

Arbitrary precision edytuj

Pomoc edytuj

Błędy kompilacji edytuj

error: variable or field declared void edytuj

  • W rzeczywistości nie jest to problem że funkcja jest „void”, ale problem z parametrami funkcji. Kompilator g++, który wyświetla nieprzydatny komunikat o błędzie.[4]

Przypisy edytuj

  1. stackoverflow question: which-c-standard-is-the-default-when-compiling-with-g
  2. Creating large arrays with GMP
  3. MPFR C++ by Pavel Holoborodko
  4. stackoverflow question: variable-or-field-declared-void