Fact-checked by Grok 2 weeks ago

FreeBASIC

FreeBASIC is a free and open-source multi-platform for the language, supporting procedural, object-oriented, and meta-programming paradigms with a syntax highly compatible to and other variants. It enables the creation of console and graphical applications, libraries, and executables that run natively on supported systems without requiring an . Initiated in September 2004 by developer Andre Victor as a code-compatible alternative to the discontinued , FreeBASIC quickly became self-hosting by November of that year and achieved its first public release (version 0.01) on November 30, 2004. Key contributors include Angelo Mottola for graphics library enhancements and Daniel R. Verkamp for the port, with ongoing development led by a team including dkl since 2010. The project, hosted on since October 2004, has evolved to include 64-bit support starting with version 1.00.0 in 2014, handling (, , ), and optimizations comparable to GCC-generated code. The latest stable release is version 1.10.1, released on December 25, 2023, with development of version 1.20.0 ongoing as of November 2025; it is licensed under the (GPL). FreeBASIC targets i386-based architectures across Windows, , , and , utilizing for , linking, and archiving to ensure portability. It offers two primary dialects: "-lang qb" for near-complete compatibility (including features like line numbers and GOSUB) and the default "-lang fb" mode, which incorporates C-style elements such as pointers, inline , and a while remaining case-insensitive. The language supports a wide range of data types, including integers (Byte to Longint), floating-point (, ), and strings (fixed-length, variable up to 2GB, Wstring for wide characters), along with user-defined types (UDTs) that enable nested structures, unions, multi-dimensional arrays (up to 8 dimensions), and procedure pointers for advanced . Notable features include thin bindings to C runtime libraries, partial C++ support, and integrations with popular APIs such as SDL for multimedia, OpenGL for graphics, GTK+ for interfaces, and the Windows API, allowing developers to build cross-platform applications with minimal modifications. Debugging is facilitated through GDB integration, and the compiler produces compact binaries, including smaller DOS executables in recent versions. Written entirely in FreeBASIC, the compiler exemplifies the language's maturity and serves as a toolset for creating software ranging from simple scripts to complex games and utilities, maintaining BASIC's accessibility while extending its capabilities to modern paradigms.

History and Development

Origins and Early Development

FreeBASIC was founded in 2004 by Andre Victor, known online as V1ctor, as a free and open-source alternative to , initially targeting 32-bit Windows platforms. The project originated from Victor's prior work on QuickBASIC extensions, such as libraries for enhanced floating-point performance and SVGA graphics support. The core goal was to maintain syntactic compatibility with QuickBASIC, allowing existing codebases to compile with minimal changes, while introducing modern capabilities absent in its predecessor. Key additions included support for pointers to enable direct memory manipulation and dynamic allocation functions for flexible resource management, bridging the gap between legacy BASIC simplicity and contemporary programming needs. This approach positioned FreeBASIC as an evolution of the QBASIC and QuickBASIC lineage, preserving their accessible dialect for procedural programming. In its formative years, development remained a solitary effort by , who bootstrapped the initial using for before transitioning to self-compilation. Community involvement emerged later, drawn by the project's open-source ethos and fidelity to QuickBASIC's ecosystem. From inception, FreeBASIC adopted the GNU General Public License version 2 or later (GPLv2+), ensuring its , runtime libraries, and tools remained freely modifiable and distributable.

Key Milestones and Releases

FreeBASIC's development has seen several pivotal advancements in platform support and version stability. In December 2004, Angelo Mottola (known online as Lillo) contributed the initial port to , expanding the beyond its Windows origins and enabling cross-platform capabilities. This was followed in January 2005 by the DOS port, developed by Daniel R. Verkamp, which utilized the toolchain to support 32-bit protected-mode execution under and compatible environments like . Between 2006 and 2010, the project benefited from significant contributions by developers including Angelo Mottola (Lillo), who focused on Windows-specific enhancements, graphics library improvements, and overall code maturation. During this period, experimental support for 64-bit targets began to emerge in internal discussions, though full implementation came later; additionally, an early port for console was achieved in July 2005 using version 0.13, allowing basic executable generation but remaining experimental. The port remains experimental and unmaintained since around 2010 due to evolving platform architectures like the Xbox 360. Major releases marked key stability and feature milestones, transitioning FreeBASIC from compatibility toward a more independent, multi-platform language. The following table summarizes principal versions:
VersionRelease DateKey Notes
0.90.0August 6, 2006Initial multi-platform maturity with mature -gen backend, extensive bug fixes for Win32 and I/O, and OOP enhancements.
1.00.0September 24, 2014Stable milestone release celebrating 10 years; introduced full 64-bit support for Windows and (requiring ), reduced binary sizes, and numerous bug fixes.
1.05.0January 31, 2016Focused on bug fixes and minor refinements to core functionality.
1.06.0February 18, 2019Primarily addressed bug fixes for reliability across platforms.
1.10.1December 25, 2023Latest stable release as of 2025, incorporating bug fixes, updated build tools, and improved cross-platform compatibility; includes both 32-bit and 64-bit compilers in default Windows packages.
Since 2023, development has progressed on the master branch toward version 1.20.0, emphasizing enhanced code generation reliability and backend improvements, with critical fixes merged from the 1.10 branch; as of November 2025, no official release has occurred.

Current Status and Community

FreeBASIC continues to be maintained by the FreeBASIC Development Team, with leadership under Jeff Marshall since 2017, following Daniel Klauer (dkl) from 2010 to 2017 and founder Andre Victor from 2004 to 2010; contributions accepted through the project's repository and official forums. The project, which originated in 2004, has seen steady volunteer involvement from a core group of 28 contributors on , focusing on bug fixes, documentation updates, and platform compatibility enhancements. The community remains active primarily on the freebasic.net forums, where users discuss compiler issues, share code snippets, and propose improvements, with ongoing threads on bug reports and feature requests extending into late 2025. Peak online activity reached 2,756 users on September 11, 2025, reflecting sustained engagement among hobbyists, educators, and developers interested in . Forum sections dedicated to general discussion and project-related topics host thousands of posts, including recent conversations on stability and tool integrations as of 2025. As of November 2025, no major stable release has occurred since version 1.10.1, issued on December 25, 2023, with development efforts emphasizing stability and reliability for this version. An experimental branch for version 1.20.0, initiated in 2023, incorporates backend improvements such as updated code generation and bug squashes, with community-built snapshots available and referenced in forum posts throughout 2025. The compiler integrates with for cross-compilation across platforms like Windows, , and , enabling multi-platform builds without native dependencies on each target. FreeBASIC maintains its design philosophy of , eschewing automatic garbage collection to align with its heritage and provide fine-grained control for performance-critical applications. Looking ahead, community discussions highlight interest in bolstering C++ interoperability through refined bindings and backend optimizations, though the project lacks a formalized public roadmap.

Language Fundamentals

Platforms and Compatibility

FreeBASIC supports 32-bit and 64-bit variants of Windows and Linux as primary operating systems, along with protected-mode DOS environments such as FreeDOS, and FreeBSD. The compiler also targets other Unix-like systems including NetBSD and OpenBSD through cross-compilation options. While early versions included support for the Xbox console, this has been discontinued due to lack of maintenance following the departure of the original porter. Architecturally, FreeBASIC generates code directly for x86 (i386) and x86-64 processors, with support for 32-bit and 64-bit ARM architectures achieved by emitting intermediate C code for compilation. Cross-compilation is facilitated by integrating with , allowing the compiler to produce binaries for different platforms from a host system by using target-specific assembler, linker, and related tools. The FreeBASIC compiler itself is written entirely in FreeBASIC, making it self-hosting and highly portable without reliance on non-portable external tools. For DOS targets, it requires a DPMI server like CWSDPMI.exe to enable 32-bit protected-mode execution on 16-bit DOS systems. To ensure with legacy variants, FreeBASIC provides a compatibility mode activated via the -lang qb compiler flag, which enables full support for syntax including unstructured GOSUB/[RETURN](/page/RETURN) statements, the ON ERROR handler, and legacy graphics statements like GFX. This mode omits modern FreeBASIC features such as dimensioning requirements and line numbers to closely emulate behavior. In contrast, the default -lang fb mode incorporates extensions while maintaining core compatibility. Compiled FreeBASIC programs have no runtime dependencies beyond standard OS libraries, such as msvcrt.dll on Windows, libc and libpthread on Linux, or DPMI services on DOS. The compiler supports both static and dynamic linking options, allowing developers to produce standalone executables or libraries that link against system shared objects as needed. FreeBASIC handles Unicode through support for UTF-8, UTF-16LE/BE, and UTF-32LE/BE encodings in source files and headers, with automatic conversion to ASCII where applicable. The WSTRING type facilitates wide-character strings for Unicode text processing. Multi-threading is implemented via platform-specific OS APIs, such as Win32 threads on Windows and POSIX pthreads on Linux and Unix variants, using built-in functions like ThreadCreate for spawning concurrent processes. This approach ensures portability across supported platforms without introducing additional runtime overhead.

Core Features and Paradigms

FreeBASIC is a multi-paradigm programming language that supports , through user-defined types (UDTs), and via directives. The procedural paradigm allows for structured code organization using subroutines and functions, maintaining compatibility with syntax for straightforward . Object-oriented features are implemented using UDTs, which can include methods, constructors, and destructors; inheritance is achieved via the Extends keyword, enabling derived types to inherit fields and methods from base types, while polymorphism is supported through virtual procedures and (RTTI) derived from the built-in Object type. is available for UDTs, allowing custom definitions of operators like +, -, and Cast to enhance expressiveness, with both global and member operator declarations permitted. Metaprogramming capabilities include text-replacement macros defined with #DEFINE for single-line substitutions and #MACRO/#ENDMACRO for multi-line expansions, facilitating code generation and abstraction at compile time. The language provides a rich set of built-in data types for handling various data needs. Integer types range from 8-bit Byte and unsigned UByte to 64-bit LongInt and ULongInt, with Integer and UInteger adapting to platform pointer size (32-bit or 64-bit). Floating-point types include 32-bit Single, 64-bit Double, and extended-precision Long Double (size varying by platform: 80-bit, 96-bit, or 128-bit). String types support dynamic allocation up to 2 GB with String for ANSI/UTF-8 characters and WString for wide characters (Unicode), alongside null-terminated ZString. Although lacking a native Variant type, FreeBASIC supports variant-like behavior through the Any type or custom UDTs that can hold multiple data kinds, compatible with COM/OLE automation. Memory management in FreeBASIC is manual, without built-in garbage collection, requiring explicit allocation and deallocation using Alloc and Free functions. Pointers follow C-like syntax with unlimited indirection levels, enabling and dynamic data structures. Arrays support up to eight dimensions with a total size limit of 2 GB, including dynamic and fixed-size variants for flexible data handling. Procedure pointers allow runtime binding to subroutines and functions, supporting callbacks and higher-order programming. Additional core capabilities include inline assembly using (GAS) with Intel syntax for low-level optimizations within Asm blocks. The compiler optionally transcompiles FreeBASIC code to C via the -gen gcc backend, which leverages for further compilation and optimizations, improving portability and performance on supported platforms. This backend generates native executables with GCC-like optimizations, such as inlining and , while the default -gen gas directly emits assembly for efficient x86/x86_64 .

Syntax and Dialects

Basic Syntax Elements

FreeBASIC programs follow a line-based structure where code executes sequentially from top to bottom without requiring an explicit main procedure or an END statement to terminate the program, though the END statement can be used optionally to exit and return control to the operating system with an error code. This design aligns with traditional BASIC dialects, allowing implicit program flow while supporting modular organization through procedures. Variables and data structures are declared using statements like Dim for scalars, arrays, or dynamic allocations, and Type for user-defined types (UDTs), which encapsulate fields of various data types into a single composite structure. Control flow in FreeBASIC is managed through conditional and iterative statements that assume familiarity with QuickBASIC syntax. The If...Then statement evaluates a condition and executes a block if true, optionally with Else or ElseIf for alternatives; for multiple conditions, Select Case compares an expression against literal values or ranges in Case clauses. Loops include While...Wend for condition-checked iterations, Do...Loop variants (Do While/Until...Loop or Loop While/Until) for flexible entry/exit testing, and For...Next for counted iterations over a range with optional Step increments. Procedures are defined with Sub for void routines or Function for returning values, while Declare prototypes external or forward declarations to enable modular code without immediate implementation. Operators in FreeBASIC support standard arithmetic operations such as addition (+), subtraction (-), multiplication (*), division (/), integer division (), modulus (Mod), exponentiation (^), and negation (-); these apply to numeric types with promotion rules for mixed operands. Logical operators include And (conjunction), Or (disjunction), Xor (exclusive or), Eqv (equivalence), Imp (implication), and Not (negation), which perform bitwise or boolean evaluations depending on context. String concatenation uses the & operator (or + in some dialects, but & is preferred for clarity), appending operands without spaces or type conversion issues. FreeBASIC maintains compatibility with QuickBASIC statements like Gosub for subroutine calls. Comments are added using a single apostrophe (') or Rem for inline or line-start remarks, which ignore the rest of the line; in the FB dialect, multi-line comments are delimited by /* and */. Error handling employs On Error to set a global or local handler routine, jumping to a label or line on runtime errors like division by zero or file I/O failures; Resume returns control to the error line or next, while the Err function retrieves the error code and Erl the line number. Preprocessor directives facilitate conditional and code inclusion, beginning with # and processed before . #Include inserts external source files at the directive's position, #Define creates macros for text substitution, and #If (with #Else, #Elif, #Endif) compiles blocks based on constant expressions or defined symbols via #Ifdef/#Ifndef. The following example illustrates basic syntax elements in a simple program that declares variables, uses , and handles a potential :
Dim As [Integer](/page/Integer) counter = 0
Dim As [String](/page/String) message = "Hello"

' Increment and check counter
For counter = 1 To 5
    If counter [Mod](/page/Mod) 2 = 0 Then
        Print message & " (even: "; counter; ")"
    Else
        Select Case counter
        Case 1
            Print message & " (first)"
        Case 3, 5
            Print message & " (odd: "; counter; ")"
        End Select
    End If
Next

' Error handling example
On Error Goto ErrorHandler
Dim As Integer result = 10 \ 0  ' Division by zero
Resume Next
ErrorHandler:
Print "Error "; Err; " at line "; Erl
Resume Next
This code demonstrates declarations, loops, conditionals, operators, comments, and error handling without requiring dialect-specific features.

Dialect Variants

FreeBASIC supports multiple dialects that adjust the language's syntax and feature set to balance compatibility with legacy BASIC interpreters like and against modern programming capabilities. These dialects are selected via the -lang compiler option or the #lang directive in , allowing developers to tailor the process to specific needs such as old code or leveraging contemporary features. The default dialect, -lang fb, provides full access to FreeBASIC's modern extensions, including with classes and , namespaces, templates, and stricter type checking that prohibits implicit declarations and type suffixes on (though numeric literals can use suffixes like f for single-precision floats). This mode disables legacy constructs such as DEFINT, GOSUB/[RETURN](/page/Return), COMMON SHARED, and OPTION statements to enforce cleaner, more robust code, while enabling advanced paradigms like and scope blocks. It is recommended for new projects aiming for production-quality software with enhanced safety and extensibility. In contrast, the -lang qb dialect prioritizes compatibility with and by restricting the language to legacy features and enabling QB-specific statements such as SCREEN for modes, COLOR for text attributes, and implicit variable handling where undeclared variables default to single-precision floats. This mode excludes modern elements like multi-threading, classes, namespaces, and variable initialization in declarations, while supporting core features like pointers and dynamic memory allocation, permitting forward-referenced function calls with CALL and treating DATA statements as literal strings without quotes. It impacts available keywords by reserving QB-style ones and limits library access to avoid conflicts with extended features, making it suitable for direct ports of older code. The -lang deprecated dialect offers with FreeBASIC versions prior to 0.17b (specifically up to 0.16b), allowing obsolete constructs like COMMON SHARED for global variable sharing across modules, GOSUB/RETURN for unstructured subroutines, and ON GOSUB for indirect jumps, but it discourages use due to its planned removal in future releases. This mode supports features from early FreeBASIC but prohibits advancements such as classes, , and constructors/destructors within TYPE definitions, resulting in a less secure and maintainable compared to other dialects. Developers are advised to migrate to -lang fblite (a hybrid that builds on deprecated features while adding limited modern support like GOSUB via Option Gosub) for ongoing legacy compatibility without the deprecation risks. Switching dialects via compiler flags like -lang qb or the #lang "qb" directive in code affects not only syntax parsing—such as enabling periods in variable names or numeric labels in QB mode—but also the availability of keywords and libraries, potentially requiring code adjustments for cross-dialect portability. For instance, QB-specific statements like SCREEN and COLOR are unavailable in fb mode, while fb's templates and OOP are inaccessible in qb or deprecated modes. The trade-offs among dialects reflect their design goals: -lang qb facilitates and by mimicking QuickBASIC's forgiving but sacrifices advanced paradigms and features, whereas -lang fb supports with robust tools like stricter checking and at the cost of requiring explicit declarations and excluding unstructured control flows. The deprecated dialect, while useful for maintaining very old FreeBASIC code, offers minimal benefits for new work and may introduce maintenance challenges due to its obsolescence.

Libraries and Graphics

Standard Libraries

FreeBASIC's standard libraries consist of built-in runtime functions and header files that provide bindings to the , system APIs, and select external libraries, enabling core programming tasks without external dependencies. These libraries emphasize compatibility with and C conventions, focusing on essential utilities rather than a comprehensive collection like the C++ Standard Template Library. The CRT bindings, included via the crt.bi header file, offer C-style interfaces for fundamental operations, with sub-headers like stdio.bi, math.bi, and string.bi organizing prototypes by category. For file I/O, CRT functions such as fopen, fread, and fwrite handle stream-based reading and writing, while FreeBASIC's built-in statements like Open (for modes including , , and ), Input (for reading values or lines), and (for formatted output) provide a more BASIC-oriented approach. Mathematical computations are supported by built-in functions including (sine of an angle in radians), (cosine), and (), supplemented by CRT equivalents like sin_, cos_, and sqrt in math.bi. String manipulation includes built-in functions such as Left (extracts leftmost characters), Right (extracts rightmost characters), and Instr (finds the first occurrence of a ), alongside CRT utilities like strcat (), strlen (), and strcpy (copying). System-level libraries address platform interactions through dedicated headers. Console I/O can use built-in Input and Print or CRT functions like and via stdio.bi. Threading support includes built-in functions such as ThreadCreate (starts a new thread with a pointer and parameters) and Mutex (via MutexCreate, MutexLock, and MutexUnlock for synchronization). On Windows, the windows.bi header and win/ subdirectory provide bindings to the , including functions like MessageBox for GUI elements. For and other systems, POSIX compliance is achieved through CRT headers, enabling standard system calls. External bindings are implemented as thin header files (.bi) in the inc/ directory, allowing direct access to popular APIs without requiring full wrapper libraries. These include headers for (multimedia and input handling), (game development utilities), GTK+ (GUI toolkit), and (3D graphics rendering via GL/gl.bi), where developers link against the respective shared or static libraries using compiler options or #inclib directives. Header files serve as the primary mechanism for library integration, containing declarations, constants, and prototypes that can be included with #include once "filename.bi" to enable function calls across platforms. The , particularly crt.bi, extends this with utilities for , including C-style dynamic allocation via malloc, free, and realloc, alongside FreeBASIC's built-in Allocate, Deallocate, New, and Delete for heap-based objects and arrays. Error and is managed through the ON ERROR statement, which redirects runtime errors (e.g., file not found) to a labeled handler or resumes execution, with the Err capturing error codes.

Graphics and Multimedia Support

FreeBASIC's graphics capabilities are primarily provided by the built-in FBgfx library, a rasterizer that enables 2D rendering without requiring by default. This library recreates QuickBASIC-era graphics commands while adding support for modern features like multiple backbuffers for page flipping and via ScreenPtr and ScreenLock. Key drawing functions include Line for straight lines, Circle for ellipses and arcs, and PSet for individual pixels, allowing developers to construct complex visuals programmatically. Sprite management is handled through Get and Put operations, which capture and blit image data between buffers or the screen. Graphics modes are initialized using the SCREEN statement, which supports QB-compatible mode numbers (e.g., mode 13 for 320x200 with 256 colors) or extended resolutions via flags for windowed, fullscreen, or modes. On Windows, FBgfx leverages as its backend for efficient rendering, while on it uses , though both prioritize software rendering over GPU acceleration unless explicitly bound to external . Resolutions range from legacy VGA standards like 640x480 up to high-definition sizes such as 3200x1800, depending on system capabilities, with no strict upper limit imposed by the library itself but practical constraints from memory and hardware. In the QB dialect (-lang qb), legacy statements like for vector-based and for flood-filling enclosed areas are fully available, ensuring compatibility with older codebases. For multimedia, FreeBASIC offers basic audio support through the PLAY statement, which generates tones, musical notes, and simple melodies using or PCM modes, akin to QuickBASIC's implementation. Advanced audio handling, including playback of formats like , OGG, , and with effects such as 3D positioning and streaming, requires binding to external libraries like or , both of which have official headers included in FreeBASIC distributions. supports a wide range of formats and platforms (Win32 and ) with features like channel management and tag reading, while provides similar functionality with beta support and easy integration for music loading and playback. Native video playback or capture is not supported, necessitating third-party libraries for such needs. Although FBgfx enables rudimentary 3D effects through software-based projections and transformations, it lacks built-in GPU shaders, hardware-accelerated rendering, or advanced 3D primitives, relying on external bindings to or for complex scenes. In QB mode, graphics availability aligns closely with limitations, such as integer-only coordinates in , but extends to higher color depths and resolutions unavailable in the original. Overall, these tools prioritize simplicity and portability for applications, with multimedia extensions filling gaps in audio processing.

Programming Examples

Simple Programs

FreeBASIC's straightforward syntax enables beginners to create functional programs quickly, starting with basic output and control structures. The following examples illustrate fundamental operations in the default -lang fb dialect, where variables must be explicitly declared using the Dim statement. A quintessential introductory program is the "Hello World" example, which outputs a greeting to the console and pauses before terminating. This snippet demonstrates the statement for display, for user-visible delay, and End to conclude execution:
Print "Hello, World!"
Sleep
End
When compiled and run, it prints "Hello, World!" and waits for a keypress. Variable declaration and basic arithmetic operations are handled through the Dim keyword, which allocates for typed variables such as , a 32-bit signed suitable for whole numbers. Consider this example that declares an integer, performs , and outputs the result:
Dim x As Integer = 5
Print x * 2
Sleep
End
Executing this yields "10" on the console, showcasing assignment, arithmetic operators, and integration with Print. For interactive programs, FreeBASIC supports user input via the Input statement within looping constructs like Do...Loop, allowing repeated data entry until a condition is met. This example prompts for numbers in a loop, summing them until the user enters zero:
Dim num As Integer, total As Integer = 0
Print "Enter numbers (0 to stop):"
Do
    Input "", num
    If num <> 0 Then total += num
Loop While num <> 0
Print "Total: "; total
End
The program accumulates inputs and displays the sum, highlighting conditional checks and loop control for basic user interaction. File operations in FreeBASIC use the Open statement to access s for output, Write or for content addition, and Close to finalize. The following creates and writes to a simple :
Open "example.txt" For Output As #1
[Print](/page/Print) #1, "This is a test line."
Close #1
[Print](/page/Print) "File written."
Sleep
End
Upon running, it generates "example.txt" containing the specified line, demonstrating sequential file handling without advanced error checking.

Advanced Usage Examples

FreeBASIC enables sophisticated via user-defined types that support constructors, destructors, and , allowing for reusable and extensible code structures similar to classes in other languages. The following example defines a 2D type with a constructor, a parameterized constructor, and an overloaded addition . It includes a destructor for cleanup and demonstrates , , and output, with error checking for valid values.
freebasic
Type Vector2D
    Public:
        x As Single
        y As Single
    Declare Constructor()
    Declare Constructor(ByVal xx As Single, ByVal yy As Single)
    Declare Operator + (ByRef other As Vector2D) As Vector2D
    Declare Destructor()
Private:
    Declare Sub Validate()
End Type

Constructor Vector2D()
    This.x = 0.0f
    This.y = 0.0f
    This.Validate()
End Constructor

Constructor Vector2D(ByVal xx As Single, ByVal yy As Single)
    This.x = xx
    This.y = yy
    This.Validate()
End Constructor

Sub Vector2D.Validate()
    If [Abs](/page/ABS)(This.x) > 1e6 Or [Abs](/page/ABS)(This.y) > 1e6 Then
        [Print](/page/Print) "Error: Vector values too large."
        This.x = 0.0f
        This.y = 0.0f
    End If
End Sub

Operator Vector2D.+ (ByRef other As Vector2D) As Vector2D
    Return Type(This.x + other.x, This.y + other.y)
End Operator

Destructor Vector2D()
    ' Cleanup if extended with dynamic resources
End Destructor

' Usage example
Dim v1 As Vector2D(3.0f, 4.0f)
Dim v2 As Vector2D(1.0f, 2.0f)
Dim v3 As Vector2D = v1 + v2
Print "Result: ("; v3.x; ", "; v3.y; ")"  ' Outputs: (4, 6)
[Sleep](/page/Sleep)
This code is compilable under the QB dialect and highlights initialization, overload , and basic error handling. For graphics programming, FreeBASIC's built-in FBgfx library provides hardware-accelerated rendering with support for multiple s, color depths, and primitives. The example below sets up a 320x200 screen in mode, uses a loop to render animated lines with a cycling color palette, and includes cleanup on exit.
freebasic
#Include "fbgfx.bi"

ScreenRes 320, 200, 8
ScreenSet(0, 1)  ' Double buffering
Dim As [Integer](/page/Integer) page = 0
Dim As [Single](/page/Single) angle = 0.0f
Dim As UByte color = 1

Do
    ScreenSet(page, (page Xor 1))
    ScreenSync
    
    Cls  ' Clear with [black](/page/Black)
    Locate 10, 10
    Print "Animated Lines - Press any key to exit"
    
    ' Draw rotating lines with color
    Dim As [Integer](/page/Integer) x1 = 160 + [Cos](/page/Cos)(angle) * 100
    Dim As [Integer](/page/Integer) y1 = 100 + [Sin](/page/Sin)(angle) * 50
    Line (160, 100)-(x1, y1), color, 0  ' Thin line
    Line (x1, y1)-(x1 + 50, y1 + 50), (color + 1) [Mod](/page/Mod) 16, B  ' Filled [box](/page/Box)
    
    angle += 0.1f
    color = (color + 1) [Mod](/page/Mod) 16  ' Cycle palette
    
    page Xor= 1
    If Inkey <> "" Then Exit Do
    Sleep 50, 1  ' [Frame rate control](/page/Frame_rate_control)
Loop

Screen 0  ' Cleanup to console
This 18-line snippet demonstrates screen initialization, page flipping for smooth animation, primitive drawing with Line, color manipulation, and proper mode restoration to prevent hangs. FreeBASIC integrates external libraries like SDL2 through provided bindings, enabling cross-platform window management and event handling without relying solely on FBgfx. The SDL2 header allows creation of resizable windows and polling for events such as quit signals, with error checking via null pointers.
freebasic
#Include Once "SDL2/SDL.bi"
#Include Once "SDL2/SDL_main.bi"

If SDL_Init(SDL_INIT_VIDEO) <> 0 Then
    Print "SDL_Init Error: " & SDL_GetError()
    End 1
End If

Var As SDL_Window Ptr window = SDL_CreateWindow("SDL Window Example", _
    SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, _
    SDL_WINDOW_SHOWN Or SDL_WINDOW_RESIZABLE)
If window = 0 Then
    Print "Window Creation Error: " & SDL_GetError()
    SDL_Quit()
    End 1
End If

Dim As SDL_Event event
Dim As Integer running = 1

While running
    While SDL_PollEvent(@event)
        Select Case event.type
        Case SDL_QUIT
            running = 0
        Case SDL_KEYDOWN
            If event.key.keysym.sym = SDL_SCANCODE_ESCAPE Then running = 0
        End Select
    Wend
    
    ' Render loop placeholder (e.g., clear and draw)
    SDL_Delay(16)  ' ~60 [FPS](/page/FPS)
Wend

SDL_DestroyWindow(window)
SDL_Quit()
This example, approximately 15 lines, shows SDL initialization, window creation with flags, event polling in a loop for quit and key events, and resource cleanup to avoid leaks; it compiles with the linked. Multi-threading in FreeBASIC uses ThreadCreate to spawn parallel tasks, with mutexes ensuring safe access to shared resources like console output during computations. The following demonstrates creating multiple threads for simulated parallel pi approximation (using simple integrals), synchronized via a mutex, with handles stored for waiting and final cleanup.
freebasic
Const As [Integer](/page/Integer) MAX_THREADS = 4
Dim Shared As Any Ptr pi_mutex
Dim Shared As [Double](/page/Double) pi_total = 0.0

Sub ComputePiSlice(ByVal data As Any Ptr)
    Dim As Integer id = CInt(data)
    Dim As Double slice = 0.0, step = 1.0 / (MAX_THREADS * 1000000)
    Dim As Double x
    For i As Integer = id To 999999 Step MAX_THREADS
        x = (i + 0.5) * step
        slice += 4.0 * (1.0 / (1.0 + x * x))
    Next
    slice *= step
    
    MutexLock(pi_mutex)
    pi_total += slice
    Print "Thread"; id; "computed slice:"; slice
    MutexUnlock(pi_mutex)
End Sub

pi_mutex = MutexCreate()
If pi_mutex = 0 Then Print "Mutex creation failed": End 1

Dim As Any Ptr threads(MAX_THREADS - 1)
For i As [Integer](/page/Integer) = 0 To MAX_THREADS - 1
    threads(i) = ThreadCreate(@ComputePiSlice, CPtr(Any Ptr, i))
    If threads(i) = 0 Then
        [Print](/page/Print) "Thread creation failed for"; i
        Exit For
    End If
Next

For i As [Integer](/page/Integer) = 0 To MAX_THREADS - 1
    If threads(i) <> 0 Then ThreadWait(threads(i))
Next

[Print](/page/Print) "Approximate pi (sum slices):"; pi_total

MutexDestroy(pi_mutex)
Sleep
This 20-line code spawns four threads for parallel computation, uses mutex-locking for thread-safe printing and accumulation to avoid interleaving and race conditions, waits on all handles for completion, and destroys the mutex, ensuring no resource leaks; it requires the threaded (-mt).

References

  1. [1]
    FreeBASIC Language | Home
    FreeBASIC is a high-level programming language supporting procedural, object-orientated and meta-programming paradigms, with a syntax compatible to Microsoft ...About · FreeBASIC Manual · Freebasic.net Forum · Gallery
  2. [2]
    About - FreeBASIC Language
    FreeBASIC is not a "new" BASIC language. You don't need to learn much new if you are familiar with any Microsoft-BASIC variant.
  3. [3]
    Project History - FreeBASIC Wiki Manual | FBWiki
    Project History · FreeBASIC 1.00.0 release, 10 years after project start · 64-bit support (Windows and Linux, needs GCC) · Smaller DOS binaries (0.90 regression) ...
  4. [4]
  5. [5]
    About - FreeBASIC Wiki Manual | FBWiki
    The FreeBASIC project is a set of cross-platform development tools initially created by Andre Victor, consisting of a compiler, GNU-based assembler, ...
  6. [6]
    FreeBASIC and QBasic
    FreeBASIC is designed as an official successor of sorts to a high level compiler for MS-DOS titled QuickBASIC, which compiled BASIC code.<|separator|>
  7. [7]
    History of FreeBASIC
    Jan 15, 2010 · In December of 2004, Angelo Mottola ported FreeBASIC to Linux—another major step. The DOS port followed a month later, on January 31st, 2005. ...
  8. [8]
    DOS related FAQ - FreeBASIC Wiki Manual | FBWiki
    Feb 26, 2019 · The FreeBASIC port to DOS is based on the DJGPP port of the GNU toolchain to 32-bit protected-mode DOS. The current maintainer of this port is DrV.Missing: 2005 | Show results with:2005
  9. [9]
    Frequently Asked Questions - FreeBASIC Wiki Manual | FBWiki
    Dec 28, 2020 · The first versions of FreeBASIC were developed exclusively by V1ctor. Later versions gained contributions from many people, including Lillo, who ...
  10. [10]
    Frequently Asked Questions - FreeBASIC Wiki Manual | FBWiki
    14. The port is on hold until the GCC backend port is complete, because it is believed that this port will fix the Xbox port.Missing: 64- bit 2006-2010 Lillo
  11. [11]
    Version 1.10.1 Released - freebasic.net
    FreeBASIC version 1.10.1 - A multi-platform BASIC Compiler The DOWNLOADS you are MOST LIKELY looking for.Missing: 0.90 1.00 1.05 1.06<|separator|>
  12. [12]
    Freebasic 1.20.0 Development
    Jun 11, 2023 · With the release of fbc 1.10.0 completed, time to move on to the next version. Currently there is: Patches for fbc 1.10.x
  13. [13]
    freebasic/fbc - GitHub
    FreeBASIC - A multi-platform BASIC Compiler Copyright (C) 2004-2025 The FreeBASIC development team. Official site: https://freebasic.net/ Forum: https:// ...<|control11|><|separator|>
  14. [14]
    Index page - freebasic.net
    News. Topics: 40, Posts: 45. Last post Version 1.10.1 Released by ... Most users ever online was 2756 on Sep 11, 2025 13:48. Statistics. Total posts ...News · Freebasic.net - FreeBASIC · Community Discussion · Beginners<|control11|><|separator|>
  15. [15]
    Community Discussion - freebasic.net
    Community Discussion. General discussion for topics related to the FreeBASIC project or its community. 2199 topics.Missing: branch | Show results with:branch
  16. [16]
    Stability Question - freebasic.net
    May 5, 2025 · I see that the latest version on SourceForge for FreeBASIC is v1.10.1 dated 2023-12-25. According to the "Welcome" in the documentation I ...
  17. [17]
  18. [18]
    FreeBASIC Language | Home
    ### Summary of FreeBASIC (https://www.freebasic.net/)
  19. [19]
  20. [20]
    About - FreeBASIC Language
    FreeBASIC currently runs on 64/32-bit Windows, Linux, and DOS (a 16-bit DOS is good enough, although FreeBASIC itself and compiler output are 32-bit) and also ...
  21. [21]
    Compiler Option: -target - FreeBASIC Wiki Manual | FBWiki
    <os> can be one of: android; linux; cygwin; darwin; freebsd; netbsd; openbsd. <arch> can be one of: arm; aarch64; powerpc or ppc; powerpc64 or ppc64 ...
  22. [22]
    Got an XBOX - freebasic.net
    Apr 6, 2009 · The basic concept of the xbox port is very simple: You replace the mingw stuff with openxdk stuff. OpenXDK works by replacing the standard libc ...Missing: 64- bit support 2006-2010 Lillo
  23. [23]
    FreeBASIC OpenBSD package
    Oct 24, 2017 · FreeBASIC supports Windows, DOS, Xbox, Linux and other Unix platforms. The compiler, fbc, currently supports direct code generation for i386- ...
  24. [24]
  25. [25]
    Requirements - FreeBASIC Wiki Manual | FBWiki
    Oct 31, 2020 · FreeBASIC needs Windows 98+ with msvcrt.dll, Linux needs libc, libm, libpthread, libdl, libncurses, and DOS needs a DPMI server and CWSDPMI.exe.
  26. [26]
    Differences from QB - FreeBASIC Wiki Manual | FBWiki
    Differences from QB. FreeBASIC introduced a -lang command-line option, that is used to change the language compatibility mode. Use the -lang qb option when ...
  27. [27]
    FreeBASIC Dialects - FreeBASIC Wiki Manual | FBWiki
    This option will evolve into a better compatibility with QuickBASIC/QBasic code. To compile FreeBASIC sources from 0.16b, use the -lang deprecated option.
  28. [28]
    WString - FreeBASIC Documentation
    When processing source files, FreeBASIC can parse ASCII files with Unicode escape sequences (\u), UTF-8, UTF-16LE, UTF-16BE, UTF-32LE and UTF-32BE. The ...
  29. [29]
    Multi-Threading - FreeBASIC Wiki Manual | FBWiki
    Nov 30, 2020 · Multi-threading programming allows to spawn concurrent process flow. It is most effective on multi-processor or multi-core systems.Missing: APIs | Show results with:APIs
  30. [30]
    Threading Support Functions - FreeBASIC - Documentation & Help
    These procedures allow for multithreaded programming. Threads and conditional variables can be created and destroyed, and so-called mutexes can be obtained ...
  31. [31]
    Most Important Features - FreeBASIC Wiki Manual | FBWiki
    Feb 10, 2016 · Besides ASCII files with Unicode escape sequences (\u), FreeBASIC can parse UTF-8, UTF-16LE, UTF-16BE, UTF-32LE and UTF-32BE source (.bas) ...<|separator|>
  32. [32]
    Inheritance Polymorphism - FreeBASIC Wiki Manual | FBWiki
    Inheritance polymorphism (sub-type polymorphism) is the concept of providing a single interface to entities that can have different types.Missing: oriented features
  33. [33]
  34. [34]
    Operator Overloading - FreeBASIC Wiki Manual | FBWiki
    Unlike procedures, operators can be overloaded by default, so the Overload keyword is not necessary when declaring custom operators. At least one of the ...Missing: programming | Show results with:programming
  35. [35]
    #DEFINE - FreeBASIC Wiki Manual | FBWiki
    Nov 20, 2020 · #define allows to declare text-based preprocessor macros. Once the compiler has seen a #define, it will start replacing further occurrences of identifier with ...
  36. [36]
    Macros - FreeBASIC Wiki Manual | FBWiki
    Macros are named code segments that are substituted to their names each time they are encountered in a program. Macros offer a powerful way to extend the ...
  37. [37]
    Standard Data Types - FreeBASIC Wiki Manual | FBWiki
    Jul 4, 2019 · Integer types. Types that store integer values, whose range is determined by the size of the data type and its signedness. ; Floating-point types.
  38. [38]
  39. [39]
    Introduction to the Type Def - FreeBASIC Wiki Manual | FBWiki
    Feb 6, 2018 · FreeBASIC offers two composite data types, the Type and Union. Types. FreeBASIC allows you to group several data types into a unified structure ...<|control11|><|separator|>
  40. [40]
  41. [41]
    Compiler Option: -gen - FreeBASIC Wiki Manual | FBWiki
    The -gen compiler option sets the backend code emitter and assembler. If this option is not specified, the default is -gen gas for x86 and -gen gcc for x86_64.
  42. [42]
    END (Statement) - FreeBASIC Wiki Manual | FBWiki
    Used to exit the program, and return to the operating system. An optional integer return value can be specified to indicate an error code to the system.
  43. [43]
    Variables - FreeBASIC Wiki Manual | FBWiki
    Apr 15, 2016 · In FreeBASIC, variables can be defined using the Dim statement. Variables are available for later access depending on where and how the Dim ...
  44. [44]
  45. [45]
    TYPE (UDT) - FreeBASIC Wiki Manual | FBWiki
    Mar 24, 2025 · Type is used to declare custom data types containing one or more data fields, including integer types, floating point types, fixed-size or variable-length ( ...Missing: variants | Show results with:variants
  46. [46]
    IF...THEN - FreeBASIC Wiki Manual | FBWiki
    Sep 28, 2021 · If...Then is a way to make decisions. It is a mechanism to execute code only if a condition is true, and can provide alternative code to execute based on more ...Missing: While | Show results with:While
  47. [47]
    SELECT CASE - FreeBASIC Wiki Manual | FBWiki
    Sep 28, 2021 · Select Case executes specific code depending on the value of an expression. The expression is evaluated once, and compared against each Case, in order.Missing: While | Show results with:While
  48. [48]
    WHILE...WEND - FreeBASIC Wiki Manual | FBWiki
    Like all control flow statements, the While statement can be nested, that is, it can be used in a statement block of another While statement.Missing: Select | Show results with:Select
  49. [49]
  50. [50]
  51. [51]
  52. [52]
  53. [53]
  54. [54]
    Arithmetic Operators - FreeBASIC Wiki Manual | FBWiki
    Aug 8, 2007 · The mathematical operators perform mathematical operations with the values of their operands and return the results. Operator + (Add). Returns ...Missing: logical string
  55. [55]
  56. [56]
  57. [57]
    Comments - FreeBASIC Wiki Manual | FBWiki
    Mar 13, 2016 · The comment statement: Rem​​ A source code statement beginning with Rem indicates that the line is comment and will not be compiled. In FreeBASIC ...
  58. [58]
    REM - FreeBASIC Wiki Manual | FBWiki
    Indicates comments in the source code. Syntax: Rem ... A source code line beginning with Rem indicates that the line is a comment and will not be compiled.
  59. [59]
    Error Handling - FreeBASIC Wiki Manual | FBWiki
    Jun 28, 2020 · On Error sets an error handling routine which the program will jump to when an error is found. On Error Goto 0 disables the error handling.
  60. [60]
    ON ERROR - FreeBASIC Wiki Manual | FBWiki
    On Error triggers a jump to an error handler when an error occurs. Such errors can be triggered by built-in statements such as Open, or when the Error ...
  61. [61]
    RESUME - FreeBASIC Wiki Manual | FBWiki
    May 14, 2018 · Resume is used in the traditional QB error handling mechanism within an error handler (called by On Error) to return execution to the line that caused the ...
  62. [62]
    Preprocessor - FreeBASIC Wiki Manual | FBWiki
    #DEFINE. Creates a single-line text-replacement macro. #MACRO and #ENDMACRO. Creates a multi-line text-replacement ...
  63. [63]
  64. [64]
    Control Flow Statements - FreeBASIC Wiki Manual | FBWiki
    Aug 13, 2020 · Executes a block of statements while or until a condition is met. Intra-loop control. CONTINUE WHILE, CONTINUE FOR and CONTINUE DO. Prematurely ...
  65. [65]
    Compiler Option: -lang - FreeBASIC Wiki Manual | FBWiki
    The `-lang` option changes how source code is interpreted, providing QuickBASIC-like behavior. Dialects include fb, fblite, qb, and deprecated.
  66. [66]
  67. [67]
  68. [68]
    C Standard Library Functions - FreeBASIC Wiki Manual | FBWiki
    Apr 9, 2018 · This is a list of function prototypes in the standard C library in alphabetical order and a list of prototypes grouped by functionality.
  69. [69]
    Using Prebuilt Libraries - FreeBASIC Wiki Manual | FBWiki
    FreeBASIC is distributed with many headers for common or popular libraries. The headers allow a programmer to use functions available in these existing static ...
  70. [70]
  71. [71]
    Mathematical Functions - FreeBASIC Wiki Manual | FBWiki
    Mar 14, 2016 · Mathematical Functions ; SIN. Returns the sine of an angle. ; ASIN. Returns the arcsine of a number. ; COS. Returns the cosine of an angle. ; ACOS.
  72. [72]
    String Functions - FreeBASIC Wiki Manual | FBWiki
    Mar 14, 2016 · Removes surrounding substrings or characters on the left and right side of a string. INSTR. Returns the first occurrence of a substring or ...
  73. [73]
    THREADCREATE - FreeBASIC Wiki Manual | FBWiki
    Apr 29, 2023 · In order to exchange data between multiple threads, including a thread and the main part of the program, mutexes must be used. These mutual ...
  74. [74]
    Threading Support Functions - FreeBASIC Wiki Manual | FBWiki
    FreeBASIC provides functions for multithreaded programming, including starting threads, creating mutexes, and managing conditional variables. Functions like ...
  75. [75]
    External Libraries Index - FreeBASIC Wiki Manual | FBWiki
    Feb 6, 2021 · This is the list of external library bindings currently included in FreeBASIC. Visit the link shown for each individual library below to see more information.
  76. [76]
    Header Files (.bi) - FreeBASIC Wiki Manual | FBWiki
    A header file is a special kind of source file that typically only contains preprocessor statements, defines, declarations, prototypes, constants, enumerations ...
  77. [77]
  78. [78]
    GfxLib - FreeBASIC graphics library overview
    GfxLib is the built-in graphics library included in FreeBASIC. As well as re-creating every QuickBASIC graphics command, GfxLib has built-in commands to handle ...
  79. [79]
    SCREEN (GRAPHICS) - FreeBASIC Wiki Manual | FBWiki
    ### Summary of SCREEN Command (Graphics Modes) - FreeBASIC Wiki
  80. [80]
    Beginner help for DOS version - freebasic.net
    Oct 30, 2020 · The 3200x1800 resolution was obtained using both DOS and WINDOWS version of FreeBASIC (latest versions) - DOS version on a Rufus formated USB ...
  81. [81]
    DRAW - FreeBASIC Wiki Manual | FBWiki
    ### Summary of DRAW Statement (FreeBASIC Wiki)
  82. [82]
    PAINT - FreeBASIC Wiki Manual | FBWiki
    ### Summary of PAINT Statement (FreeBASIC Wiki)
  83. [83]
    Sound (description) - freebasic.net
    Feb 5, 2021 · The library includes functions for setting midi and PCM sound modes, playing musical notes, producing sound of a specific frequency, and ...
  84. [84]
    FMOD - FreeBASIC Wiki Manual | FBWiki
    ### Summary of FMOD Library Support in FreeBASIC
  85. [85]
    BASS - FreeBASIC Wiki Manual | FBWiki
    - **BASS Library Overview**: Audio library for Windows, with a beta version for Linux.
  86. [86]
    Hello World - FreeBASIC Wiki Manual | FBWiki
    Feb 10, 2016 · Type code in an editor, save as 'hello.bas', then use `fbc hello.bas` to create an executable, which will output 'Hello World'.
  87. [87]
    INPUT - FreeBASIC Wiki Manual | FBWiki
    Nov 12, 2020 · Input "Would you like to enter some more numbers"; yn yn = LCase(yn) Loop Until yn = "y" Or yn = "n" Loop While LCase(yn) = "y". Differences ...
  88. [88]
    WHILE - FreeBASIC Wiki Manual | FBWiki
    Jan 25, 2020 · While specifies that a loop block will continue if the condition following it evaluates as true. This condition is checked during each loop iteration.Missing: Select | Show results with:Select
  89. [89]
    File I/O with FreeBASIC - FreeBASIC Wiki Manual | FBWiki
    Oct 30, 2021 · In FreeBASIC, there are 4 possible ways to perform file I/O: 1. Using the built-in BASIC commands like Open , Get, Put, and Close. This way is mostly portable.
  90. [90]
    CONSTRUCTOR - FreeBASIC Wiki Manual | FBWiki
    ### Summary of Type Constructors from https://www.freebasic.net/wiki/KeyPgConstructor
  91. [91]
    LINE (GRAPHICS) - FreeBASIC Wiki Manual | FBWiki
    ### Summary of Code Examples for Drawing Lines and Boxes with Colors in FBgfx
  92. [92]
    None
    Nothing is retrieved...<|separator|>
  93. [93]
    THREADCREATE - FreeBASIC Wiki Manual | FBWiki
    ### Summary of ThreadCreate Example with Mutex for Synchronization
  94. [94]
    Mutual Exclusion - FreeBASIC Wiki Manual | FBWiki
    ### Visual Example of Mutex with Threads for Parallel Computation