Commit 13aac507 for tesseract

commit 13aac507cbc4b255791d34aa91126d71d703736a
Author: Stefan Weil <sw@weilnetz.de>
Date:   Fri Nov 27 13:46:50 2026 +0100

    Fix compiler warnings

    Builds with g++ and clang printed warnings, both with the default
    options (CMake with g++ 13) and with -Wall -Wextra -Wpedantic, which
    the cross build for Windows uses. Fix all of them for the library,
    the training tools and the unit tests.

    - Comparisons of signed and unsigned integers (-Wsign-compare).
      TrainingSampleSet::SetupFontIdMap() now resizes the vector of
      counts instead of adding one element at a time, and skips a
      negative font id, which OrganizeByFontAndClass() reports.
    - Conditional expressions with an enumerator and an integer.
    - Unused variables, parameters and a global variable which was only
      written (stillRunning in pgedit.cpp).
    - MasterTrainer passed the member fontinfo_table_ to members which
      were declared before it. Declare it first.
    - Initialize PROTO_SET_STRUCT by value instead of with memset, which
      g++ rejects for a class with a non-trivial constructor
      (-Wclass-memaccess).
    - CHAR_FRAGMENT::set_unichar() copied with strncpy
      (-Wstringop-truncation). Copy with memcpy and clear the rest.
    - "#pragma comment" is only for MSVC, and FD_SET() compared a SOCKET
      with an int (clang for Windows).
    - Unit tests: missing parentheses around the operator ! of ICOORD
      and FCOORD in points_test.cc (-Wlogical-not-parentheses) and a
      comment with a backslash at the end of the line (-Wcomment).

    Three changes only avoid false warnings from g++ 13 with -O3
    (-Wstringop-overflow, -Wmaybe-uninitialized): the loop in
    TFile::FReadEndian() now also stops at count, a variable in
    TessdataManager::CombineDataFiles() is initialized, and two helper
    functions of the unit tests build their buffers in another way.

    Tested with g++ 13 and clang 18 (CMake and autotools, aarch64), with
    g++ 14 and clang 19 (autotools, x86-64) and with the cross build for
    Windows (clang 23). The text and hOCR output of the test images did
    not change.

    Assisted-by: Claude Fable 5.2 (Anthropic)
    Signed-off-by: Stefan Weil <sw@weilnetz.de>

diff --git a/src/ccmain/pgedit.cpp b/src/ccmain/pgedit.cpp
index c0075909..aa90f61e 100644
--- a/src/ccmain/pgedit.cpp
+++ b/src/ccmain/pgedit.cpp
@@ -101,7 +101,6 @@ enum ColorationMode {

 static ScrollView *image_win;
 static ParamsEditor *pe;
-static bool stillRunning = false;

 static ScrollView *bln_word_window = nullptr; // baseline norm words

@@ -254,7 +253,7 @@ void PGEventHandler::Notify(const SVEvent *event) {
     pe->Notify(event);
   } // These are handled by ParamsEditor
   else if (event->type == SVET_EXIT) {
-    stillRunning = false;
+    // Nothing to do.
   } else if (event->type == SVET_MENU) {
     if (event->parameter == "true") {
       myval = 'T';
@@ -359,7 +358,6 @@ void Tesseract::pgeditor_main(int width, int height, PAGE_RES *page_res) {
   }

   recog_done = false;
-  stillRunning = true;

   build_image_window(width, height);
   word_display_mode.set(DF_EDGE_STEP);
diff --git a/src/ccutil/serialis.cpp b/src/ccutil/serialis.cpp
index 615fde91..296cd68c 100644
--- a/src/ccutil/serialis.cpp
+++ b/src/ccutil/serialis.cpp
@@ -241,7 +241,9 @@ size_t TFile::FReadEndian(void *buffer, size_t size, size_t count) {
   auto num_read = FRead(buffer, size, count);
   if (swap_ && size != 1) {
     char *char_buffer = static_cast<char *>(buffer);
-    for (size_t i = 0; i < num_read; ++i, char_buffer += size) {
+    // FRead never returns more than count. Saying so here avoids false
+    // warnings (-Wstringop-overflow) from GCC 13 with -O3.
+    for (size_t i = 0; i < num_read && i < count; ++i, char_buffer += size) {
       ReverseN(char_buffer, size);
     }
   }
diff --git a/src/ccutil/tessdatamanager.cpp b/src/ccutil/tessdatamanager.cpp
index 35b1d91f..16e962fa 100644
--- a/src/ccutil/tessdatamanager.cpp
+++ b/src/ccutil/tessdatamanager.cpp
@@ -271,7 +271,7 @@ bool TessdataManager::CombineDataFiles(const char *language_data_path_prefix,
                                        const char *output_filename) {
   // Load individual tessdata components from files.
   for (auto filesuffix : kTessdataFileSuffixes) {
-    TessdataType type;
+    TessdataType type = TESSDATA_NUM_ENTRIES;
     ASSERT_HOST(TessdataTypeFromFileSuffix(filesuffix, &type));
     std::string filename = language_data_path_prefix;
     filename += filesuffix;
diff --git a/src/ccutil/unicharcompress.cpp b/src/ccutil/unicharcompress.cpp
index b3dd440f..4edae6f0 100644
--- a/src/ccutil/unicharcompress.cpp
+++ b/src/ccutil/unicharcompress.cpp
@@ -205,7 +205,7 @@ bool UnicharCompress::ComputeEncoding(const UNICHARSET &unicharset, int null_id,
   // Now renumber Han to make all codes unique. We already added han_offset to
   // all Han. Now separate out the radical, stroke, and count codes for Han.
   int code_offset = 0;
-  for (int i = 0; i < RecodedCharID::kMaxCodeLen; ++i) {
+  for (uint32_t i = 0; i < RecodedCharID::kMaxCodeLen; ++i) {
     int max_offset = 0;
     for (unsigned u = 0; u < unicharset.size(); ++u) {
       RecodedCharID *code = &encoder_[u];
@@ -282,7 +282,7 @@ void UnicharCompress::DefragmentCodeValues(int encoded_null) {
   // Now apply the offsets.
   for (auto &c : encoder_) {
     RecodedCharID *code = &c;
-    for (int i = 0; i < code->length(); ++i) {
+    for (uint32_t i = 0; i < code->length(); ++i) {
       int value = (*code)(i);
       code->Set(i, value + offsets[value]);
     }
diff --git a/src/ccutil/unicharset.h b/src/ccutil/unicharset.h
index 9cffaa7b..55f58452 100644
--- a/src/ccutil/unicharset.h
+++ b/src/ccutil/unicharset.h
@@ -64,8 +64,9 @@ public:
     set_natural(natural);
   }
   inline void set_unichar(const char *uch) {
-    strncpy(this->unichar, uch, sizeof(this->unichar));
-    this->unichar[UNICHAR_LEN] = '\0';
+    const size_t len = strnlen(uch, UNICHAR_LEN);
+    memcpy(this->unichar, uch, len);
+    memset(this->unichar + len, 0, sizeof(this->unichar) - len);
   }
   inline void set_pos(int p) {
     this->pos = p;
diff --git a/src/classify/intproto.cpp b/src/classify/intproto.cpp
index 33a29d96..d38255ad 100644
--- a/src/classify/intproto.cpp
+++ b/src/classify/intproto.cpp
@@ -286,9 +286,8 @@ int AddIntProto(INT_CLASS_STRUCT *Class) {

   if (Class->NumProtos > MaxNumIntProtosIn(Class)) {
     int ProtoSetId = Class->NumProtoSets++;
-    auto ProtoSet = new PROTO_SET_STRUCT;
+    auto ProtoSet = new PROTO_SET_STRUCT();
     Class->ProtoSets[ProtoSetId] = ProtoSet;
-    memset(ProtoSet, 0, sizeof(*ProtoSet));

     /* reallocate space for the proto lengths and install in class */
     Class->ProtoLengths.resize(MaxNumIntProtosIn(Class));
@@ -607,8 +606,7 @@ INT_CLASS_STRUCT::INT_CLASS_STRUCT(int MaxNumProtos) :

   for (int i = 0; i < NumProtoSets; i++) {
     // allocate space for a proto set, install in class, and initialize
-    auto ProtoSet = new PROTO_SET_STRUCT;
-    memset(ProtoSet, 0, sizeof(*ProtoSet));
+    auto ProtoSet = new PROTO_SET_STRUCT();
     ProtoSets[i] = ProtoSet;

     // allocate space for the proto lengths and install in class
@@ -859,7 +857,7 @@ INT_TEMPLATES_STRUCT *Classify::ReadIntTemplates(TFile *fp) {
     if (MaxNumIntProtosIn(Class) > 0) {
       Class->ProtoLengths.resize(MaxNumIntProtosIn(Class));
       if (fp->FRead(&Class->ProtoLengths[0], sizeof(uint8_t), MaxNumIntProtosIn(Class)) !=
-          MaxNumIntProtosIn(Class)) {
+          static_cast<size_t>(MaxNumIntProtosIn(Class))) {
         tprintf("Bad read of inttemp!\n");
       }
     }
diff --git a/src/classify/intproto.h b/src/classify/intproto.h
index 0223e3f5..893231c6 100644
--- a/src/classify/intproto.h
+++ b/src/classify/intproto.h
@@ -154,7 +154,7 @@ inline constexpr int PPrunerWordIndexFor(int I) { return (I % PROTOS_PER_PROTO_S
 inline constexpr int PPrunerBitIndexFor(int I) { return I % PROTOS_PER_PP_WERD; }
 inline constexpr uint32_t PPrunerMaskFor(int I) { return 1u << PPrunerBitIndexFor(I); }

-inline constexpr int MaxNumClassesIn(const INT_TEMPLATES_STRUCT *T) { return T->NumClassPruners * CLASSES_PER_CP; }
+inline constexpr unsigned MaxNumClassesIn(const INT_TEMPLATES_STRUCT *T) { return T->NumClassPruners * CLASSES_PER_CP; }
 inline constexpr bool LegalClassId(int c) { return c >= 0 && c < MAX_NUM_CLASSES; }
 inline constexpr bool UnusedClassIdIn(INT_TEMPLATES_STRUCT *T, int c) { return T->Class[c] == nullptr; }
 inline constexpr INT_CLASS_STRUCT *&ClassForClassId(INT_TEMPLATES_STRUCT *T, int c) { return T->Class[c]; }
diff --git a/src/textord/baselinedetect.cpp b/src/textord/baselinedetect.cpp
index 62dbaec8..9e7be7cf 100644
--- a/src/textord/baselinedetect.cpp
+++ b/src/textord/baselinedetect.cpp
@@ -576,7 +576,6 @@ void BaselineBlock::PrepareForSplineFitting(ICOORD page_tr, bool remove_noise) {
 void BaselineBlock::FitBaselineSplines(bool enable_splines,
                                        bool show_final_rows, Textord *textord) {
   double gradient = tan(skew_angle_);
-  FCOORD rotation(1.0f, 0.0f);

   if (enable_splines) {
     textord->make_spline_rows(block_, gradient, show_final_rows);
diff --git a/src/training/common/errorcounter.cpp b/src/training/common/errorcounter.cpp
index 70599814..9e0972fc 100644
--- a/src/training/common/errorcounter.cpp
+++ b/src/training/common/errorcounter.cpp
@@ -64,7 +64,9 @@ double ErrorCounter::ComputeErrorRate(ShapeClassifier *classifier, int report_le
     TrainingSample *mutable_sample = it->MutableSample();
     int page_index = mutable_sample->page_num();
     Image page_pix =
-        0 <= page_index && page_index < page_images.size() ? page_images[page_index] : nullptr;
+        0 <= page_index && static_cast<size_t>(page_index) < page_images.size()
+            ? page_images[page_index]
+            : nullptr;
     // No debug, no keep this.
     classifier->UnicharClassifySample(*mutable_sample, page_pix, 0, INVALID_UNICHAR_ID, &results);
     bool debug_it = false;
@@ -128,7 +130,9 @@ void ErrorCounter::DebugNewErrors(ShapeClassifier *new_classifier, ShapeClassifi
     TrainingSample *mutable_sample = it->MutableSample();
     int page_index = mutable_sample->page_num();
     Image page_pix =
-        0 <= page_index && page_index < page_images.size() ? page_images[page_index] : nullptr;
+        0 <= page_index && static_cast<size_t>(page_index) < page_images.size()
+            ? page_images[page_index]
+            : nullptr;
     // No debug, no keep this.
     old_classifier->UnicharClassifySample(*mutable_sample, page_pix, 0, INVALID_UNICHAR_ID,
                                           &results);
diff --git a/src/training/common/mastertrainer.h b/src/training/common/mastertrainer.h
index 5e37d757..12966410 100644
--- a/src/training/common/mastertrainer.h
+++ b/src/training/common/mastertrainer.h
@@ -252,6 +252,9 @@ private:
   UNICHARSET unicharset_;
   // Original feature space. Subspace mapping is contained in feature_map_.
   IntFeatureSpace feature_space_;
+  // Font metrics gathered from multiple files.
+  // The sample sets below keep a reference to it, so it must come first.
+  FontInfoTable fontinfo_table_;
   TrainingSampleSet samples_;
   TrainingSampleSet junk_samples_;
   TrainingSampleSet verify_samples_;
@@ -259,8 +262,6 @@ private:
   ShapeTable master_shapes_;
   // Flat shape table has each unichar/font id pair in a separate shape.
   ShapeTable flat_shapes_;
-  // Font metrics gathered from multiple files.
-  FontInfoTable fontinfo_table_;
   // Array of xheights indexed by font ids in fontinfo_table_;
   std::vector<int32_t> xheights_;

diff --git a/src/training/common/trainingsampleset.cpp b/src/training/common/trainingsampleset.cpp
index d9f7adae..9338ae9f 100644
--- a/src/training/common/trainingsampleset.cpp
+++ b/src/training/common/trainingsampleset.cpp
@@ -595,9 +595,13 @@ void TrainingSampleSet::SetupFontIdMap() {
   // Number of samples for each font_id.
   std::vector<int> font_counts;
   for (auto &sample : samples_) {
-    const int font_id = sample->font_id();
-    while (font_id >= font_counts.size()) {
-      font_counts.push_back(0);
+    if (sample->font_id() < 0) {
+      // Invalid. OrganizeByFontAndClass reports it.
+      continue;
+    }
+    const auto font_id = static_cast<size_t>(sample->font_id());
+    if (font_id >= font_counts.size()) {
+      font_counts.resize(font_id + 1);
     }
     ++font_counts[font_id];
   }
diff --git a/src/training/unicharset/lang_model_helpers.cpp b/src/training/unicharset/lang_model_helpers.cpp
index a7b68de5..3447e670 100644
--- a/src/training/unicharset/lang_model_helpers.cpp
+++ b/src/training/unicharset/lang_model_helpers.cpp
@@ -109,7 +109,8 @@ bool WriteRecoder(const UNICHARSET &unicharset, bool pass_through, const std::st
   if (pass_through) {
     recoder.SetupPassThrough(unicharset);
   } else {
-    int null_char = unicharset.has_special_codes() ? UNICHAR_BROKEN : unicharset.size();
+    int null_char = unicharset.has_special_codes() ? static_cast<int>(UNICHAR_BROKEN)
+                                                   : static_cast<int>(unicharset.size());
     tprintf("Null char=%d\n", null_char);
     if (!recoder.ComputeEncoding(unicharset, null_char, radical_table_data)) {
       tprintf("Creation of encoded unicharset failed!!\n");
diff --git a/src/training/unicharset/lstmtrainer.cpp b/src/training/unicharset/lstmtrainer.cpp
index 51619e4d..5682fd23 100644
--- a/src/training/unicharset/lstmtrainer.cpp
+++ b/src/training/unicharset/lstmtrainer.cpp
@@ -1112,8 +1112,8 @@ void LSTMTrainer::InitCharSet() {

 // Helper computes and sets the null_char_.
 void LSTMTrainer::SetNullChar() {
-  null_char_ = GetUnicharset().has_special_codes() ? UNICHAR_BROKEN
-                                                   : GetUnicharset().size();
+  null_char_ = GetUnicharset().has_special_codes() ? static_cast<int>(UNICHAR_BROKEN)
+                                                   : static_cast<int>(GetUnicharset().size());
   RecodedCharID code;
   recoder_.EncodeUnichar(null_char_, &code);
   null_char_ = code(0);
@@ -1216,7 +1216,7 @@ void LSTMTrainer::DisplayTargets(const NetworkIO &targets,
 // truth labels and the rest is padded with the null_char_.
 bool LSTMTrainer::ComputeTextTargets(const std::vector<int> &truth_labels,
                                      NetworkIO *targets) {
-  if (truth_labels.size() > targets->Width()) {
+  if (truth_labels.size() > static_cast<size_t>(targets->Width())) {
     tprintf("Error: transcription %s too long to fit into target of width %d\n",
             DecodeLabels(truth_labels).c_str(), targets->Width());
     return false;
diff --git a/src/training/unicharset/unicharset_training_utils.cpp b/src/training/unicharset/unicharset_training_utils.cpp
index a9d6d2f5..9c55a586 100644
--- a/src/training/unicharset/unicharset_training_utils.cpp
+++ b/src/training/unicharset/unicharset_training_utils.cpp
@@ -136,7 +136,7 @@ void SetupBasicProperties(bool report_errors, bool decompose, UNICHARSET *unicha
     } else {
       unicharset->set_normed(unichar_id, unichar_str);
     }
-    ASSERT_HOST(unicharset->get_other_case(unichar_id) < unicharset->size());
+    ASSERT_HOST(static_cast<size_t>(unicharset->get_other_case(unichar_id)) < unicharset->size());
   }
   unicharset->post_load_setup();
 }
diff --git a/src/viewer/svutil.cpp b/src/viewer/svutil.cpp
index 58fc9bc3..1ff89e60 100644
--- a/src/viewer/svutil.cpp
+++ b/src/viewer/svutil.cpp
@@ -37,7 +37,9 @@
 #include <vector>

 #ifdef _WIN32
-#  pragma comment(lib, "Ws2_32.lib")
+#  ifdef _MSC_VER
+#    pragma comment(lib, "Ws2_32.lib")
+#  endif
 #  include <winsock2.h> // for fd_set, send, ..
 #  include <ws2tcpip.h> // for addrinfo
 #else
@@ -216,7 +218,11 @@ char *SVNetwork::Receive() {
     // Set the flags to return when the stream_ is ready to be read.
     fd_set readfds;
     FD_ZERO(&readfds);
+#ifdef _WIN32
+    FD_SET(static_cast<SOCKET>(stream_), &readfds);
+#else
     FD_SET(stream_, &readfds);
+#endif

     int i = select(stream_ + 1, &readfds, nullptr, nullptr, &tv);

diff --git a/unittest/baseapi_test.cc b/unittest/baseapi_test.cc
index 34079bff..8d979752 100644
--- a/unittest/baseapi_test.cc
+++ b/unittest/baseapi_test.cc
@@ -432,7 +432,7 @@ TEST_F(TesseractTest, LSTMGeometryTest) {
     tess_blob_box.rotate(block->re_rotation());
     // verify that each of LSTM's character boxes lies close to within
     // tesseract's word box
-    for (int i = 0; i < word->box_word->length(); ++i) {
+    for (unsigned i = 0; i < word->box_word->length(); ++i) {
       TBOX lstm_blob_box = word->box_word->BlobBox(i);
       // LSTM character box should not spill out of tesseract word box
       // by more than a few pixels in any direction
diff --git a/unittest/intfeaturemap_test.cc b/unittest/intfeaturemap_test.cc
index 228628ca..ce245a64 100644
--- a/unittest/intfeaturemap_test.cc
+++ b/unittest/intfeaturemap_test.cc
@@ -96,7 +96,6 @@ TEST_F(IntFeatureMapTest, Exhaustive) {
         EXPECT_LE(theta_delta, dtheta);
       } else {
         ++bad_offsets;
-        INT_FEATURE_STRUCT f = map.InverseIndexFeature(index);
       }
     }
   }
diff --git a/unittest/intproto_test.cc b/unittest/intproto_test.cc
index ee5b6e20..ff934c7f 100644
--- a/unittest/intproto_test.cc
+++ b/unittest/intproto_test.cc
@@ -28,6 +28,7 @@

 #include <cstdint>
 #include <cstdio>
+#include <cstring> // for memcpy
 #include <string>
 #include <vector>

@@ -50,8 +51,9 @@ std::vector<char> MakeInttemp(int32_t version_id, uint32_t num_class_pruners,
                               uint8_t num_proto_sets = 0, uint16_t num_protos = 0) {
   std::vector<char> data;
   auto append = [&data](const void *p, size_t n) {
-    const char *b = static_cast<const char *>(p);
-    data.insert(data.end(), b, b + n);
+    const size_t old_size = data.size();
+    data.resize(old_size + n);
+    memcpy(&data[old_size], p, n);
   };
   append(&unicharset_size, sizeof(unicharset_size));
   append(&version_id, sizeof(version_id));
@@ -88,8 +90,9 @@ std::vector<char> MakeLegacyInttemp(int32_t version_id, uint32_t num_classes,
                                     const std::vector<int32_t> &class_ids) {
   std::vector<char> data;
   auto append = [&data](const void *p, size_t n) {
-    const char *b = static_cast<const char *>(p);
-    data.insert(data.end(), b, b + n);
+    const size_t old_size = data.size();
+    data.resize(old_size + n);
+    memcpy(&data[old_size], p, n);
   };
   uint32_t num_class_pruners = 1;
   append(&unicharset_size, sizeof(unicharset_size));
diff --git a/unittest/lstm_test.cc b/unittest/lstm_test.cc
index 4b3d4ac2..4c99c709 100644
--- a/unittest/lstm_test.cc
+++ b/unittest/lstm_test.cc
@@ -15,10 +15,10 @@
 //
 // Use --xsize 800 for text2image to be similar to original training data.
 //
-// tesstrain.py --fonts_dir /usr/share/fonts --lang eng \
-// --linedata_only   --noextract_font_properties --langdata_dir ../langdata_lstm \
-// --tessdata_dir ../tessdata --output_dir ~/tesseract/test/testdata \
-// --fontlist "Arial" --maxpages 10
+// tesstrain.py --fonts_dir /usr/share/fonts --lang eng
+//   --linedata_only   --noextract_font_properties --langdata_dir ../langdata_lstm
+//   --tessdata_dir ../tessdata --output_dir ~/tesseract/test/testdata
+//   --fontlist "Arial" --maxpages 10
 //

 #include "lstm_test.h"
diff --git a/unittest/mastertrainer_test.cc b/unittest/mastertrainer_test.cc
index 30f4bf4e..3cf5e03c 100644
--- a/unittest/mastertrainer_test.cc
+++ b/unittest/mastertrainer_test.cc
@@ -78,8 +78,8 @@ public:
   // If keep_this (a shape index) is >= 0, then the results should always
   // contain keep_this, and (if possible) anything of intermediate confidence.
   // The return value is the number of classes saved in results.
-  int ClassifySample(const TrainingSample &sample, Image page_pix, int debug, UNICHAR_ID keep_this,
-                     std::vector<ShapeRating> *results) override {
+  int ClassifySample(const TrainingSample &sample, Image /*page_pix*/, int /*debug*/,
+                     UNICHAR_ID /*keep_this*/, std::vector<ShapeRating> *results) override {
     results->clear();
     // Everything except the first kNumNonReject is a reject.
     if (++num_done_ > kNumNonReject) {
diff --git a/unittest/points_test.cc b/unittest/points_test.cc
index 7a1af5c4..bd361350 100644
--- a/unittest/points_test.cc
+++ b/unittest/points_test.cc
@@ -67,7 +67,7 @@ public:
 TEST_F(PointsTest, ICooordArithmeticIsConstant) {
   static_assert(ICOORD(3, 4) == ICOORD(1, 2) + ICOORD(2, 2), "");
   static_assert(ICOORD(1, 2) - ICOORD(2, 2) == ICOORD(-1, 0), "");
-  static_assert(!ICOORD(3, 4) == ICOORD(-4, 3), "");
+  static_assert((!ICOORD(3, 4)) == ICOORD(-4, 3), "");
   static_assert(-ICOORD(3, 4) == ICOORD(-3, -4), "");
   static_assert(ICOORD(3, 4) * 2 == ICOORD(6, 8), "");
   static_assert(2 * ICOORD(3, 4) == ICOORD(6, 8), "");
@@ -89,7 +89,7 @@ TEST_F(PointsTest, FCoordsArithmeticIsConstant) {
                 "");
   static_assert(FCOORD(1.0f, 2.0f) - FCOORD(0.5f, 0.5f) == FCOORD(0.5f, 1.5f),
                 "");
-  static_assert(!FCOORD(3.0f, 4.0f) == FCOORD(-4.0f, 3.0f), "");
+  static_assert((!FCOORD(3.0f, 4.0f)) == FCOORD(-4.0f, 3.0f), "");
   static_assert(-FCOORD(3.0f, 4.0f) == FCOORD(-3.0f, -4.0f), "");
   static_assert(FCOORD(3.0f, 4.0f) * 2.0f == FCOORD(6.0f, 8.0f), "");
   static_assert(2.0f * FCOORD(3.0f, 4.0f) == FCOORD(6.0f, 8.0f), "");
diff --git a/unittest/recodebeam_test.cc b/unittest/recodebeam_test.cc
index 0fc73857..36f323e6 100644
--- a/unittest/recodebeam_test.cc
+++ b/unittest/recodebeam_test.cc
@@ -74,8 +74,9 @@ protected:
     std::string radical_data;
     CHECK_OK(file::GetContents(radical_stroke_file, &radical_data, file::Defaults()));
     CHECK(ccutil_.unicharset.load_from_file(unicharset_file.c_str()));
-    unichar_null_char_ =
-        ccutil_.unicharset.has_special_codes() ? UNICHAR_BROKEN : ccutil_.unicharset.size();
+    unichar_null_char_ = ccutil_.unicharset.has_special_codes()
+                             ? static_cast<int>(UNICHAR_BROKEN)
+                             : static_cast<int>(ccutil_.unicharset.size());
     std::string radical_str(radical_data.c_str());
     EXPECT_TRUE(recoder_.ComputeEncoding(ccutil_.unicharset, unichar_null_char_, &radical_str));
     RecodedCharID code;
@@ -174,7 +175,7 @@ protected:
     for (int i = 0; i < 2; ++i) {
       beam_search.ExtractBestPathAsWords(line_box, 1.0f, false, &ccutil_.unicharset, words);
       std::string w_decoded;
-      for (int w = 0; w < words->size(); ++w) {
+      for (unsigned w = 0; w < words->size(); ++w) {
         const WERD_RES *word = (*words)[w];
         if (w_decoded.size() < truth_utf8.size()) {
           if (!w_decoded.empty() && word->word->space()) {
@@ -446,7 +447,7 @@ TEST_F(RecodeBeamTest, DISABLED_ChiDictionary) {
   ExpectCorrect(outputs, "实学储啬投学生", nullptr, &words);
   // Each is an individual word, with permuter = top choice.
   EXPECT_EQ(7, words.size());
-  for (int w = 0; w < words.size(); ++w) {
+  for (unsigned w = 0; w < words.size(); ++w) {
     EXPECT_EQ(TOP_CHOICE_PERM, words[w]->best_choice->permuter());
   }
   // Now try again with the dictionary.
@@ -460,7 +461,7 @@ TEST_F(RecodeBeamTest, DISABLED_ChiDictionary) {
   const int kWordPerms[kNumWords] = {SYSTEM_DAWG_PERM, TOP_CHOICE_PERM, TOP_CHOICE_PERM,
                                      TOP_CHOICE_PERM, SYSTEM_DAWG_PERM};
   EXPECT_EQ(kNumWords, words.size());
-  for (int w = 0; w < kNumWords && w < words.size(); ++w) {
+  for (unsigned w = 0; w < kNumWords && w < words.size(); ++w) {
     EXPECT_STREQ(kWords[w], words[w]->best_choice->unichar_string().c_str());
     EXPECT_EQ(kWordPerms[w], words[w]->best_choice->permuter());
   }
diff --git a/unittest/tatweel_test.cc b/unittest/tatweel_test.cc
index 10e673b2..045272d8 100644
--- a/unittest/tatweel_test.cc
+++ b/unittest/tatweel_test.cc
@@ -53,7 +53,7 @@ protected:

 TEST_F(TatweelTest, UnicharsetIgnoresTatweel) {
   // This test verifies that the unicharset ignores the Tatweel character.
-  for (int i = 0; i < unicharset_.size(); ++i) {
+  for (size_t i = 0; i < unicharset_.size(); ++i) {
     const char *utf8 = unicharset_.id_to_unichar(i);
     EXPECT_EQ(strstr(utf8, reinterpret_cast<const char *>(u8"\u0640")), nullptr);
   }
@@ -83,7 +83,7 @@ TEST_F(TatweelTest, UnicharsetLoadKeepsTatweel) {
   } else {
     EXPECT_TRUE(unicharset_.load_from_file(filename.c_str()));
     int num_tatweel = 0;
-    for (int i = 0; i < unicharset_.size(); ++i) {
+    for (size_t i = 0; i < unicharset_.size(); ++i) {
       const char *utf8 = unicharset_.id_to_unichar(i);
       if (strstr(utf8, reinterpret_cast<const char *>(u8"\u0640")) != nullptr) {
         ++num_tatweel;
diff --git a/unittest/tfile_test.cc b/unittest/tfile_test.cc
index 6a180ec5..b1be2e79 100644
--- a/unittest/tfile_test.cc
+++ b/unittest/tfile_test.cc
@@ -219,11 +219,10 @@ TEST_F(TfileTest, BigEndian) {
 // trailing bytes, mirroring the count-prefixed layout the vector, string
 // and char-vector deserializers expect.
 std::vector<char> MakeCountBuffer(uint32_t count, int trailing_bytes) {
-  std::vector<char> buf;
+  std::vector<char> buf(4 + trailing_bytes, 0);
   for (int i = 0; i < 4; ++i) {
-    buf.push_back(static_cast<char>((count >> (8 * i)) & 0xFF));
+    buf[i] = static_cast<char>((count >> (8 * i)) & 0xFF);
   }
-  buf.resize(buf.size() + trailing_bytes, 0);
   return buf;
 }

diff --git a/unittest/unicharcompress_test.cc b/unittest/unicharcompress_test.cc
index dd473c90..97531989 100644
--- a/unittest/unicharcompress_test.cc
+++ b/unittest/unicharcompress_test.cc
@@ -33,7 +33,8 @@ protected:
     CHECK_OK(file::GetContents(radical_stroke_file, &radical_data, file::Defaults()));
     CHECK(unicharset_.load_from_file(unicharset_file.c_str()));
     std::string radical_str(radical_data.c_str());
-    null_char_ = unicharset_.has_special_codes() ? UNICHAR_BROKEN : unicharset_.size();
+    null_char_ = unicharset_.has_special_codes() ? static_cast<int>(UNICHAR_BROKEN)
+                                                 : static_cast<int>(unicharset_.size());
     compressed_.ComputeEncoding(unicharset_, null_char_, &radical_str);
     // Get the encoding of the null char.
     RecodedCharID code;
@@ -78,9 +79,10 @@ protected:
     }
     int code_range = compressed_.code_range();
     std::vector<RecodedCharID> times_seen(code_range, zeros);
-    for (int u = 0; u <= unicharset_.size(); ++u) {
+    const int num_unichars = unicharset_.size();
+    for (int u = 0; u <= num_unichars; ++u) {
       if (u != UNICHAR_SPACE && u != null_char_ &&
-          (u == unicharset_.size() ||
+          (u == num_unichars ||
            (unicharset_.has_special_codes() && u < SPECIAL_UNICHAR_CODES_COUNT))) {
         continue; // Not used so not encoded.
       }
@@ -89,7 +91,7 @@ protected:
       // Check round-trip encoding.
       int unichar_id;
       std::vector<UNICHAR_ID> normed_ids;
-      if (u == null_char_ || u == unicharset_.size()) {
+      if (u == null_char_ || u == num_unichars) {
         unichar_id = null_char_;
       } else {
         unichar_id = u;
@@ -208,7 +210,8 @@ TEST_F(UnicharcompressTest, DoesLigaturesWithDoubles) {
   ExpectCorrect("por");
   // Check that any unichar-id that is encoded with multiple codes has the
   // correct encoded_null_char_ in between.
-  for (int u = 0; u <= unicharset_.size(); ++u) {
+  const int num_unichars = unicharset_.size();
+  for (int u = 0; u <= num_unichars; ++u) {
     RecodedCharID code;
     int len = compressed_.EncodeUnichar(u, &code);
     if (len > 1) {
diff --git a/unittest/util/utf8/unicodetext.cc b/unittest/util/utf8/unicodetext.cc
index 04e55138..f43b6e77 100644
--- a/unittest/util/utf8/unicodetext.cc
+++ b/unittest/util/utf8/unicodetext.cc
@@ -305,8 +305,8 @@ UnicodeText::const_iterator UnicodeText::find(const UnicodeText &look) const {
   return UnsafeFind(look, begin());
 }

-UnicodeText::const_iterator UnicodeText::UnsafeFind(const UnicodeText &look,
-                                                    const_iterator start_pos) const {
+UnicodeText::const_iterator UnicodeText::UnsafeFind([[maybe_unused]] const UnicodeText &look,
+                                                    [[maybe_unused]] const_iterator start_pos) const {
   // Due to the magic of the UTF8 encoding, searching for a sequence of
   // letters is equivalent to substring search.
 #ifdef INCLUDE_TENSORFLOW