summaryrefslogtreecommitdiff
path: root/docs/handbook/libnbtplusplus/building.md
blob: 61bd5a57a311d4a82892680a1587f25df34236cc (plain)
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# Building libnbt++

## Build System

libnbt++ uses **CMake** (minimum version 3.15) as its build system. The root `CMakeLists.txt` defines the project, its options, source files, dependencies, and installation rules.

---

## Prerequisites

### Required

- **C++11 compatible compiler**: GCC 4.8+, Clang 3.3+, or MSVC 2015+
- **CMake**: Version 3.15 or later

### Optional

- **zlib**: Required for compressed NBT support (gzip/deflate). Enabled by default.
- **CxxTest**: Required for building and running unit tests. Must be discoverable by CMake's `find_package(CxxTest)`.
- **objcopy**: Required for test data embedding on Linux (binary test files are converted to object files via `objcopy`).

---

## CMake Options

The following options are available when configuring the project:

| Option             | Default | Description                                              |
|-------------------|---------|----------------------------------------------------------|
| `NBT_BUILD_SHARED` | `OFF`   | Build as a shared (dynamic) library instead of static    |
| `NBT_USE_ZLIB`     | `ON`    | Enable zlib compression support                          |
| `NBT_BUILD_TESTS`  | `ON`    | Build the unit test executables                          |
| `NBT_NAME`         | `nbt++` | Override the output library name                         |
| `NBT_DEST_DIR`     | (unset) | If set, enables install target with specified destination|

### Option Details

#### NBT_BUILD_SHARED

When `NBT_BUILD_SHARED=OFF` (default), a static library (`libnbt++.a` or `nbt++.lib`) is produced.

When `NBT_BUILD_SHARED=ON`, a shared library is produced. In this case, CMake is configured to:
- Set `CXX_VISIBILITY_PRESET` to `hidden`
- Set `VISIBILITY_INLINES_HIDDEN` to `1`
- Use the `NBT_EXPORT` macro (generated by `generate_export_header()`) to control symbol visibility

This means only classes and functions explicitly marked with `NBT_EXPORT` are exported from the shared library.

#### NBT_USE_ZLIB

When enabled (default), the build:
1. Calls `find_package(ZLIB REQUIRED)` to locate the system zlib
2. Adds the zlib source files to the library: `src/io/izlibstream.cpp` and `src/io/ozlibstream.cpp`
3. Defines the preprocessor macro `NBT_HAVE_ZLIB`
4. Links the library against `ZLIB::ZLIB`

The zlib headers (`include/io/izlibstream.h`, `include/io/ozlibstream.h`, `include/io/zlib_streambuf.h`) include `<zlib.h>` directly. If zlib is not available, these headers cannot be included.

#### NBT_NAME

Allows overriding the library target name. By default, the target is called `nbt++`, producing `libnbt++.a`. Setting `NBT_NAME=mynbt` would produce `libmynbt.a`:

```cmake
cmake -DNBT_NAME=mynbt ..
```

---

## Source Files

### Core Library Sources

The `NBT_SOURCES` variable lists all non-zlib source files:

```cmake
set(NBT_SOURCES
    src/endian_str.cpp
    src/tag.cpp
    src/tag_compound.cpp
    src/tag_list.cpp
    src/tag_string.cpp
    src/value.cpp
    src/value_initializer.cpp
    src/io/stream_reader.cpp
    src/io/stream_writer.cpp
    src/text/json_formatter.cpp)
```

### Zlib Sources (Conditional)

Only added when `NBT_USE_ZLIB=ON`:

```cmake
set(NBT_SOURCES_Z
    src/io/izlibstream.cpp
    src/io/ozlibstream.cpp)
```

---

## Building Step by Step

### 1. Clone and Navigate

```bash
git clone https://github.com/Project-Tick/Project-Tick.git
cd Project-Tick/libnbtplusplus/
```

### 2. Create Build Directory

```bash
mkdir build
cd build
```

### 3. Configure

#### Default (static library, with zlib, with tests):

```bash
cmake ..
```

#### Static library, no zlib, no tests:

```bash
cmake -DNBT_USE_ZLIB=OFF -DNBT_BUILD_TESTS=OFF ..
```

#### Shared library:

```bash
cmake -DNBT_BUILD_SHARED=ON ..
```

#### Custom library name:

```bash
cmake -DNBT_NAME=nbtpp ..
```

#### Specify a different compiler:

```bash
cmake -DCMAKE_CXX_COMPILER=clang++ ..
```

#### With install destination:

```bash
cmake -DNBT_DEST_DIR=/usr/local/lib ..
```

### 4. Build

```bash
cmake --build .
```

Or with make directly:

```bash
make -j$(nproc)
```

### 5. Run Tests (if enabled)

```bash
ctest --output-on-failure
```

### 6. Install (optional)

Only works if `NBT_DEST_DIR` was set:

```bash
cmake --install .
```

---

## Integration into Other Projects

### As a CMake Subdirectory

The most common integration method is adding libnbt++ as a subdirectory in your project:

```cmake
# In your project's CMakeLists.txt

# Optional: disable tests for the dependency
set(NBT_BUILD_TESTS OFF CACHE BOOL "" FORCE)

add_subdirectory(libnbtplusplus)

add_executable(myapp main.cpp)
target_link_libraries(myapp nbt++)
```

The `target_include_directories` in libnbt++'s CMakeLists already uses `PUBLIC`, so include paths propagate automatically:

```cmake
target_include_directories(${NBT_NAME} PUBLIC include ${CMAKE_CURRENT_BINARY_DIR})
```

The `${CMAKE_CURRENT_BINARY_DIR}` is included because `generate_export_header()` creates `nbt_export.h` in the build directory.

### Include Paths

After linking against the `nbt++` target, your code can include:

```cpp
#include <nbt_tags.h>           // All tag types
#include <io/stream_reader.h>   // Reading
#include <io/stream_writer.h>   // Writing
#include <io/izlibstream.h>     // Decompression (if NBT_USE_ZLIB)
#include <io/ozlibstream.h>     // Compression (if NBT_USE_ZLIB)
```

### Manually (without CMake)

If not using CMake, you need to:

1. Add `libnbtplusplus/include/` to your include path
2. Compile all `.cpp` files in `src/` (and `src/io/`, `src/text/`)
3. If using zlib: add `-DNBT_HAVE_ZLIB`, link against `-lz`
4. Create your own `nbt_export.h` or define `NBT_EXPORT` as empty:

```cpp
// nbt_export.h — manual version for static builds
#ifndef NBT_EXPORT_H
#define NBT_EXPORT_H
#define NBT_EXPORT
#endif
```

5. Set C++ standard to C++11 or later: `-std=c++11`

---

## The nbt_export.h Header

This header is **auto-generated** by CMake's `generate_export_header()` command at configure time. It is placed in `${CMAKE_CURRENT_BINARY_DIR}` and defines:

- `NBT_EXPORT` — marks symbols for export from shared libraries
- `NBT_NO_EXPORT` — marks symbols as hidden

For static builds, `NBT_EXPORT` typically expands to nothing. For shared builds, it maps to compiler-specific visibility attributes:

```cpp
// Example generated content (GCC/Clang)
#define NBT_EXPORT __attribute__((visibility("default")))
#define NBT_NO_EXPORT __attribute__((visibility("hidden")))
```

The binary directory is added to include paths so all source files can `#include "nbt_export.h"`.

---

## C++ Standard

The library enforces C++11 via:

```cmake
set_property(TARGET ${NBT_NAME} PROPERTY CXX_STANDARD 11)
```

This does not set `CXX_STANDARD_REQUIRED`, so CMake may use a higher standard if the compiler defaults to one. The code is compatible with C++11 through C++20+.

---

## Compile-Time Assertions

The library includes several `static_assert` checks to ensure platform compatibility:

In `src/tag.cpp`:
```cpp
static_assert(
    std::numeric_limits<float>::is_iec559 &&
    std::numeric_limits<double>::is_iec559,
    "The floating point values for NBT must conform to IEC 559/IEEE 754");
```

In `src/endian_str.cpp`:
```cpp
static_assert(CHAR_BIT == 8, "Assuming that a byte has 8 bits");
static_assert(sizeof(float) == 4, "Assuming that a float is 4 byte long");
static_assert(sizeof(double) == 8, "Assuming that a double is 8 byte long");
```

These ensure that the platform's floating-point representation matches the NBT format's IEEE 754 requirement.

---

## Platform-Specific Notes

### Linux

Tests are only supported on `x86_64` and `i686` architectures due to the use of `objcopy` for binary test data embedding:

```cmake
if(CMAKE_SYSTEM_PROCESSOR STREQUAL x86_64 OR CMAKE_SYSTEM_PROCESSOR STREQUAL amd64)
    set(OBJCOPY_TARGET "elf64-x86-64")
    set(OBJCOPY_ARCH "x86_64")
elseif(CMAKE_SYSTEM_PROCESSOR STREQUAL i686)
    set(OBJCOPY_TARGET "elf32-i386")
    set(OBJCOPY_ARCH "i386")
else()
    message(AUTHOR_WARNING "This is not a platform that would support testing nbt++")
    return()
endif()
```

### macOS / Windows

The core library compiles on any platform with a C++11 compiler and optionally zlib. However, the test suite uses Linux-specific `objcopy` commands and may not build on non-Linux platforms without modifications.

---

## Shared Library Visibility

When building as a shared library (`NBT_BUILD_SHARED=ON`), the CMake configuration applies strict visibility rules:

```cmake
if(${BUILD_SHARED_LIBS})
    set_target_properties(${NBT_NAME} PROPERTIES
        CXX_VISIBILITY_PRESET hidden
        VISIBILITY_INLINES_HIDDEN 1)
endif()
```

This means:
- All symbols are hidden by default
- Inline functions are also hidden
- Only symbols marked `NBT_EXPORT` are exported

This reduces binary size and prevents symbol collision when multiple libraries are loaded.

---

## Typical Build Output

After a successful build with all options enabled, you will have:

```
build/
├── libnbt++.a              # The static library (or libnbt++.so for shared)
├── nbt_export.h            # Generated export header
└── test/
    ├── nbttest             # Core tag tests
    ├── endian_str_test     # Endianness tests
    ├── read_test           # Reading tests
    ├── write_test          # Writing tests
    ├── zlibstream_test     # Compression tests (if NBT_USE_ZLIB)
    ├── format_test         # JSON formatter test
    └── test_value          # Value assignment tests
```

---

## Troubleshooting

### "Could not find ZLIB"

Install the zlib development package:

```bash
# Debian/Ubuntu
sudo apt install zlib1g-dev

# Fedora
sudo dnf install zlib-devel

# macOS
brew install zlib
```

Or disable zlib: `cmake -DNBT_USE_ZLIB=OFF ..`

### "Could not find CxxTest"

Install CxxTest:

```bash
# Debian/Ubuntu
sudo apt install cxxtest

# macOS
brew install cxxtest
```

Or disable tests: `cmake -DNBT_BUILD_TESTS=OFF ..`

### "nbt_export.h not found"

This file is generated at configure time. Make sure you've run `cmake ..` (the configure step) before building. If building manually without CMake, create a minimal `nbt_export.h` as described in the manual integration section above.

### Linking Errors with Shared Builds

If you see undefined symbol errors when linking against the shared library, ensure your code includes the correct headers and that `nbt_export.h` was generated during the shared build configuration. Verify `NBT_EXPORT` expands to the visibility attribute.