0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Windows11 の VSCode+Emscripten で wasm によるハローワールド (5)

Last updated at Posted at 2025-10-10

すべての記事

静的ライブラリの利用

前回 の C++ のソースコードでは printf によりコンソールに出力していた。
これを関数 log_impl() として util.cpp に記述して log() マクロを経由して利用するように変更した。

変更は上記と CMakeLists.txt のみであり、以下のようになる。

C:\wasm\project\04-use-static-lib\CMakeLists.txt
add_library, target_link_libraries を追加。

cmake_minimum_required(VERSION 3.20)
project(04_use_static_lib LANGUAGES CXX)

add_executable(04_use_static_lib func.cpp)
target_link_options(04_use_static_lib PRIVATE
    "-gsource-map"
    "-sASSERTIONS=1"
    "-sSAFE_HEAP=1"
    "--no-entry"
    "-sEXPORTED_FUNCTIONS=_malloc,_free"
    "-sEXPORTED_RUNTIME_METHODS=wasmExports,ccall,stringToUTF8OnStack,UTF8ToString,HEAP32"
)

add_library(04_use_static_lib_util STATIC util.cpp)
target_link_libraries(04_use_static_lib PRIVATE 04_use_static_lib_util)

C:\wasm\project\04-use-static-lib\util.cpp

// UTF-8N CRLF
#include <emscripten.h>
#include <cstdio>
#include <cstdarg>

extern "C"
void log_impl(const char* format...)
{
    va_list args1;

    va_start(args1, format);
    vprintf(format, args1);
    va_end(args1);
}

// EOF

C:\wasm\project\04-use-static-lib\func.cpp
呼び出す関数を printf() から log() に変更。

// UTF-8N CRLF
#include <emscripten.h>
#include <cstdio>
#include <cstring>
#include <numeric>

extern "C" void log_impl(const char* format...);
#define log(...) log_impl(__VA_ARGS__)

extern "C"
EMSCRIPTEN_KEEPALIVE
int increment(int v)
{
	log("-- increment(%d)\n", v);
	return v + 1;
}

extern "C"
EMSCRIPTEN_KEEPALIVE
char* str_repeat(const char* str, int num)
{
	log("-- str_repeat(%s, %d)\n", str, num);
	char* ret = (char*)malloc(strlen(str) * num + 1);
	ret[0] = '\0';

	for (int i=0; i<num; ++i) {
		strcat(ret, str);
	}

	return ret;
}

extern "C"
EMSCRIPTEN_KEEPALIVE
int sum(const int* nums, int len)
{
	log("-- sum(%d..%d)\n", nums[0], nums[len - 1]);
	return std::accumulate(nums, nums + len, 0);
}

// EOF

実行結果は変わらない。
次回 は log_impl() 関数を外部リンクに変更する。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?