CMake string replace command removes all the semicolons in the output content

Hi,
I want to relace the keyword “extern” with “__declspec( dllexport )” in a .c file, below is the content of CMakeLists.txt file:
=========== CMakeLists.tx ================
cmake_minimum_required(VERSION 3.12)

project(Demo1)

file(READ main.c content NEWLINE_CONSUME)

string(REPLACE “extern” “__declspec( dllexport )” content_out ${content})

file(WRITE main.cc ${content_out})

add_executable(${PROJECT_NAME} main.c)
=========== CMakeLists.tx ================

the origin content of main.c file is below:
=========== main.c ================
#include <stdio.h>
extern int add(int a, int b) {
return a + b;
}
int main(int argc, char *argv)
{
int a = 10;
int b = 20;

printf("a = %d, b = %d sum:%d\n", a, b, add(a, b));
return 0;

}
=========== main.c ================

when i exec the cmake command, seems all semicolons is removed in the result file, below is the content of result file:
=========== main.cc ================
#include <stdio.h>
__declspec( dllexport ) int add(int a, int b) {
return a + b
}
int main(int argc, char *argv)
{
int a = 10
int b = 20

printf("a = %d, b = %d sum:%d\n", a, b, add(a, b))
return 0

}
=========== main.cc ================

so is this the bug of cmake? if not, how can i replace the expected content without semicolon auto removed, thanks.

string() and file() commands expect lists as input arguments. And a list in CMake is a string where items are separated by semicolons.

Your expanded variables are not quoted, so CMake interpret it as a list. This explains why the semicolons are disappearing.

Here is a version of your code that should work (I didn’t test it):

cmake_minimum_required(VERSION 3.12)

project(Demo1)

file(READ main.c content NEWLINE_CONSUME)

string(REPLACE “extern” “__declspec( dllexport )” content_out "${content}")

file(WRITE main.cc "${content_out}")

add_executable(${PROJECT_NAME} main.c)

It works follow your suggestion, thanks a lot.